using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Newtonsoft.Json;
using System.IO;
using System.Security.Policy;
using Txgy.RBS.DTO;
using Txgy.RBS.Framework;
using Txgy.RBS.Framework.Api;
using Txgy.RBS.Framework.Models;
using Txgy.RBS.IServices;
using Txgy.RBS.Services;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Txgy.RBS.Server.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProjectInfoController : ControllerBase
    {
        private readonly IProjectInfoService _projectInfoService;
        private readonly IStationsService _stationsService;
        private readonly IGlobalConfigService _globalConfigService;
        private readonly ProcessConfig _processConfig;

        public ProjectInfoController(ILogger<ProjectInfoController> logger, IProjectInfoService projectInfoService,
            IStationsService stationsService,
            IGlobalConfigService globalConfigService,
            IConfiguration configuration)
        {
            this._projectInfoService = projectInfoService;
            this._stationsService = stationsService;
            this._globalConfigService = globalConfigService;
            this._processConfig = configuration.GetSection("process").Get<ProcessConfig>();
        }

        [HttpPost]
        public ApiResult AddProjectInfo(ProjectInfoDTO project)
        {
            //var pro=  _projectInfoService.GetProjectInfo(1);
            //  pro.id=project.id;
            //  pro.project_id = project.project_id;
            //  pro.project_name = project.project_name;
            //  pro.moni_layer = project.moni_layer;    
            //  pro.moni_num = project.moni_num;    
            return _projectInfoService.AddProjectInfo(project);
        }

        [HttpDelete("{id}")]
        public ApiResult DeleteProjectInfo(int id)
        {
            return _projectInfoService.DeleteProjectInfo(id);
        }

        [HttpPost]
        public ApiResult UpdateProjectInfo(ProjectInfoDTO project)
        {
            return _projectInfoService.UpdateProjectInfo(project);
        }

        [HttpGet("{id}")]
        public ProjectInfoDTO GetProjectInfo(int id)
        {
            return _projectInfoService.GetProjectInfo(id);
        }

        [HttpGet]
        public List<ProjectInfoDTO> GetAllProjectInfo()
        {
            return _projectInfoService.GetAllProjectInfo();
        }

        [HttpGet("{clientId}")]
        public ProjectUsedDTO GetCurrentProjectUsed(string clientId)
        {
            return _projectInfoService.GetCurrentProjectUsed(clientId);
        }

        [HttpGet]
        public ProjectUsedDTO GetCurrentProjectUsed(int projectId)
        {
            return _projectInfoService.GetCurrentProjectUsed(projectId);
        }
        [HttpPost]
        public ApiResult StartProject(ProjectUsedDTO usedDTO)
        {
            //  更新当前项目配置
            var res = new ApiResult();// _projectInfoService.UpdateCurrentProjectUsed(usedDTO);

            var curProject = this.GetProjectInfo(usedDTO.current_project_id);
            var staVpn = _stationsService.GetStationNumVpn();
            var globalConfig = _globalConfigService.GetGlobalConfig();
            if (res.Success && curProject != null)
            {

                string path = Path.Combine(globalConfig.base_path, curProject.project_name);
                if (!Directory.Exists(path))
                {
                    var direc = Directory.CreateDirectory(path);
                }
                string apmApp = Path.Combine(path, _processConfig.Apms.ProPath, _processConfig.Apms.ProName + ".exe");
                if (!System.IO.File.Exists(apmApp))
                {
                    string sourceFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "program");
                    CommonData.CopyFolder(sourceFile, Path.Combine(path, "program"));
                }
                // 修改配置文件
                string str = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + CommonData.ApmsDefaultPath);
                ApmsModel apm = JsonConvert.DeserializeObject<ApmsModel>(str);
                //station.csv
                apm.station = curProject.stationFile.file_name;
                _projectInfoService.ExportCSV(Path.Combine(path, "program\\apms", apm.station), curProject.stationFile.stations);
                //time_tab
                apm.ttime[0].ttime2d = curProject.timeTab.filename;
                System.IO.File.WriteAllText(Path.Combine(path, "program\\apms", curProject.timeTab.filename), curProject.timeTab.file_content);

                apm.is_write_slice = (curProject.local_save_result == 1) ? "YES" : "NO";
                apm.savepath = Path.Combine(globalConfig.base_path, curProject.project_name, curProject.save_result_path) ;
                apm.push2wx= (curProject.push_wx==1)? "YES" : "NO";
                apm.push_mag = curProject.push_wx_value;
                apm.push_url = globalConfig.push_wx_url;
                apm.company_id = globalConfig.push_wx_company_id;
                apm.message_id = globalConfig.push_wx_message_id;
                apm.content = globalConfig.push_wx_content;
                apm.push_key = globalConfig.push_wx_key;
                apm.channels = new List<StationChannelsModel>
                {
                    new StationChannelsModel
                    {
                         channels = curProject.channels,
                         location = curProject.location,
                         network = curProject.network,
                         station=string.Join(",", curProject.stationFile.stations.Select(p=>p.num)),
                    }
                };
                apm.xmin = (float)curProject.xmin;
                apm.xmax = (float)curProject.xmax;
                apm.ymin = (float)curProject.ymin;
                apm.ymax = (float)curProject.ymax;
                apm.zmin = (float)curProject.zmin;
                apm.zmax = (float)curProject.zmax;
                string apmJson = JsonConvert.SerializeObject(apm, Formatting.Indented);
                System.IO.File.WriteAllText(Path.Combine(path, CommonData.ApmsDefaultPath), apmJson);
                _processConfig.Apms.ProPath = Path.Combine(path, _processConfig.Apms.ProPath);

                //修改recvMqtt配置
                str = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + CommonData.RecvDefaultPath);
                var rec = JsonConvert.DeserializeObject<RecvMqttModel>(str);
                if (rec != null)
                {
                    rec.savepath = Path.Combine(globalConfig.base_path, curProject.project_name, curProject.save_waves_path);
                    rec.send2server = (curProject.send_redis == 1) ? "YES" : "NO";
                    rec.Server = curProject.mqtt_server;
                    List< StationNumVpnDTO> vpnList=new List< StationNumVpnDTO>();
                    foreach (var item in curProject.stationFile.stations)
                    {
                        var v= staVpn.Where(p => p.num == item.num).FirstOrDefault();
                        if (v != null)
                        {
                            vpnList.Add(v);
                        }
                    }
                    rec.Stations = string.Join(",", vpnList.Select(p => p.vpn_name));
                    rec.dirstruct = curProject.local_save_waves == 1 ? "NMDHM" : "NMDHM0";
                    string recvJson = JsonConvert.SerializeObject(rec, Formatting.Indented);
                    System.IO.File.WriteAllText(Path.Combine(path, CommonData.RecvDefaultPath), recvJson);
                    _processConfig.RecvMqtt.ProPath = Path.Combine(path, _processConfig.RecvMqtt.ProPath);
                }
                _processConfig.FilesWatcherService = new Framework.FileWatcherHelper.FilesWatcherService(curProject.project_id,curProject.project_name,apm.savepath);
                res= _projectInfoService.StartProject(curProject.project_name, _processConfig);
                if(res.Success)
                {
                     res = _projectInfoService.UpdateCurrentProjectUsed(usedDTO);
                     res.Data = curProject;
                }
            }
            else
            {
                res.Message = "没有查询到当前工程名称！";
            }
             return res;
        }

        [HttpPost]
        public ApiResult StopProject(ProjectUsedDTO usedDTO)
        {
            //  更新当前项目配置
            var res = _projectInfoService.DeleteCurrentProjectUsed(usedDTO.current_project_id);
            var curProject = this.GetProjectInfo(usedDTO.current_project_id);
            if (res.Success && curProject != null)
            {
                 res=  _projectInfoService.StopProject(curProject.project_name);  
                 res.Data = curProject;
            }
            return res;
        }

        [HttpGet]
        public ApiResult GetProjectProcessState(string projectName, int id)
        {
            ApiResult result = new ApiResult();

            result = _projectInfoService.GetState(projectName, id);
            return result;
        }
       
    }

}
