using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels.OperatorBindingModels;
using TravelCompanyContracts.BusinessLogicsContracts.OperatorBusinessLogicsContracts;
using TravelCompanyContracts.SearchModels.OperatorSearchModels;

namespace TravelCompanyBusinessLogic.BusinessLogic.OperatorLogics
{
    public class LoadLogic:ILoadLogic
    {
        private readonly IOperatorLogic _operatorLogic;
        private readonly IGuideLogic _guidelogic;
        private readonly ITourLogic _tourLogic;
        public LoadLogic(IOperatorLogic operatorLogic, IGuideLogic guidelogic, ITourLogic tourLogic)
        {
            _operatorLogic = operatorLogic;
            _guidelogic = guidelogic;
            _tourLogic = tourLogic;
        }

        public List<TourBindingModel> LoadToursFromJson(string jsonFilePath)
        {
            string jsonData = File.ReadAllText(jsonFilePath);
            var jsonObject = JsonConvert.DeserializeObject<Dictionary<string, List<TourBindingModel>>>(jsonData);
            var tours = jsonObject["tour"];
            return tours;
        }

        public List<GuideBindingModel> LoadGuidesFromJson(string jsonFilePath)
        {
            string jsonData = File.ReadAllText(jsonFilePath);
            var jsonObject = JsonConvert.DeserializeObject<Dictionary<string, List<GuideBindingModel>>>(jsonData);
            var guides = jsonObject["guide"];
            return guides;
        }
        public List<OperatorBindingModel> LoadOperatorsFromJson(string jsonFilePath)
        {
            string jsonData = File.ReadAllText(jsonFilePath);
            var jsonObject = JsonConvert.DeserializeObject<Dictionary<string, List<OperatorBindingModel>>>(jsonData);
            var operators = jsonObject["operator"];
            return operators;
        }

        public void LoadFromJson()
        {
            if (_operatorLogic.ReadList(null).Count == 0)
            {
                string jsonFilePath = "automatic.json";
                List<TourBindingModel> tours = LoadToursFromJson(jsonFilePath);
                List<GuideBindingModel> guides = LoadGuidesFromJson(jsonFilePath);
                List<OperatorBindingModel> operators = LoadOperatorsFromJson(jsonFilePath);
                int b = 0;
                foreach (var o in operators)
                {
                    _operatorLogic.Create(o);
                    b = _operatorLogic.ReadElement(new OperatorSearchModel { Login = o.Login }).Id;
                }
                foreach (var t in tours)
                {
                    t.OperatorId = b;
                    _tourLogic.Create(t);
                }

                foreach (var g in guides)
                {
                    g.OperatorId = b;
                    _guidelogic.Create(g);
                }
            }
        }
    }
}
