using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
using Applications.UniversalApi_WebConsole_App.Models.VeederRoot_ATG_Console_Handler_Models;
using Edge.Core.IndustryStandardInterface.ATG;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Applications.UniversalApi_WebConsole_App.Controllers
{
    public class VeederRoot_ATG_Console_Handler_Controller : Controller
    {
        private static MockAutoTankGaugeController mockAtgController;
        static VeederRoot_ATG_Console_Handler_Controller()
        {
            var tank1 = new Tank()
            {
                TankNumber = 1,
                Diameter = 1800,
                Product = new Product()
                {
                    ProductCode = "02",
                    ProductLabel = "92#"
                },
                Limit = new TankLimit() {  },
                Probe = new Probe()
                {
                    ProbeLength = 1800,
                    State = "",
                }
            };
            var tank2 = new Tank()
            {
                TankNumber = 2,
                Diameter = 1800,
                Product = new Product()
                {
                    ProductCode = "05",
                    ProductLabel = "95#"
                },
                Limit = new TankLimit()
                {
                    
                },
                Probe = new Probe()
                {
                    ProbeLength = 2800,
                    State = "",
                }
            };
            var tank3 = new Tank()
            {
                TankNumber = 3,
                Diameter = 1800,
                Product = new Product()
                {
                    ProductCode = "08",
                    ProductLabel = "98#"
                },
                Limit = new TankLimit()
                {
                    
                },
                Probe = new Probe()
                {
                    ProbeLength = 1800,
                    State = "",
                }
            };
            var tank4 = new Tank()
            {
                TankNumber = 4,
                Diameter = 1800,
                Product = new Product()
                {
                    ProductCode = "09",
                    ProductLabel = "0#"
                },
                Limit = new TankLimit()
                {
                    
                },
                Probe = new Probe()
                {
                    ProbeLength = 1800,
                    State = "",
                }
            };
            var tank5 = new Tank()
            {
                TankNumber = 5,
                Diameter = 1800,
                Product = new Product()
                {
                    ProductCode = "11",
                    ProductLabel = "-35#"
                },
                Limit = new TankLimit()
                {
                    
                },
                Probe = new Probe()
                {
                    ProbeLength = 1800,
                    State = "",
                }
            };
            mockAtgController = new MockAutoTankGaugeController(
                new List<Tank>()
                {
                    tank1,tank2,tank3,tank4,tank5
                }, SystemUnit.Metric);
        }

        // GET: VeederRoot_ATG_Console_Handler_
        public async Task<ActionResult> Index(int? tankNumber)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("User-Agent", "UniversalWebConsoleApp");

            var streamTask = client.GetStreamAsync("http://localhost:8384/u/?mn=GetAutoTankGaugeControllerAsync&pn=VeederRoot_ATG_Console_Tcp");
            var atgController = await JsonSerializer.DeserializeAsync<IAutoTankGaugeController>(await streamTask);
            return View("/Views/VeederRoot_ATG_Console_Handler/Index.cshtml", atgController);
        }


        public async Task<ActionResult> IndexMock(int? tankNumber)
        {
            var model = new AtgController()
            {
                Name = mockAtgController.MetaConfigName,
                DeviceId = mockAtgController.DeviceId,
                SystemUnit = mockAtgController.SystemUnit
            };
            if (tankNumber.HasValue)
                model.Tanks = mockAtgController.Tanks.Where(t => t.TankNumber == tankNumber.Value);
            else
                model.Tanks = mockAtgController.Tanks;
            return View("/Views/VeederRoot_ATG_Console_Handler/Index.cshtml", model);
        }


        //public async Task<IActionResult> TankProbeReadingsData(int? tankNumber)
        //{
        //    var readings = await App.AutoTankGaugeController.GetTankProbeReadingsAsync(tankNumber);
        //    if (readings == null || !readings.Any()) return NoContent();
        //    //DataPointWithStringX data = new DataPointWithStringX(DateTime.Now.ToLongTimeString(), 1999);
        //    var datas = DataPointProbeReading.From(readings.Select(r => r.Item2));
        //    return Content(JsonConvert.SerializeObject(datas, _jsonSetting), "application/json");
        //}

        // GET: VeederRoot_ATG_Console_Handler_/Details/5
        public async Task<ActionResult> Details(int? tankNumber)
        {
            if (tankNumber.HasValue)
            {
                var reading = await mockAtgController.GetTankReadingAsync(tankNumber.Value);
                if (reading == null) return NotFound();
                return Ok(new[]
                {
                   new TankReadingDto(){
                        tankNumber=   tankNumber.Value,
                        Height=   reading.Height,
                        Water=   reading.Water,
                        Temperature=   reading.Temperature,
                        Volume=   reading.Volume,
                        WaterVolume=  reading.WaterVolume,
                        TimeStamp = DateTime.Now.ToString("HH:mm:ss"),
                   }
                });
            }
            else
            {
                List<TankReadingDto> tankReadings = new List<TankReadingDto>();
                foreach (var t in mockAtgController.Tanks)
                {
                    var reading = await mockAtgController.GetTankReadingAsync(t.TankNumber);
                    if (reading == null) continue;
                    var dto = new TankReadingDto()
                    {
                        tankNumber = t.TankNumber,
                        Height = reading.Height,
                        Water = reading.Water,
                        Temperature = reading.Temperature,
                        Volume = reading.Volume,
                        WaterVolume = reading.WaterVolume,
                        TimeStamp = DateTime.Now.ToString("HH:mm:ss"),
                    };
                    tankReadings.Add(dto);
                }

                return Ok(tankReadings);
            }
        }


        // GET: VeederRoot_ATG_Console_Handler_/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: VeederRoot_ATG_Console_Handler_/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(IFormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: VeederRoot_ATG_Console_Handler_/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: VeederRoot_ATG_Console_Handler_/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: VeederRoot_ATG_Console_Handler_/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: VeederRoot_ATG_Console_Handler_/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, IFormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
}