using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EFB.Models;
using EFB.Models.JSON;
using EFB.Controllers.Form;
using EFB.Sessions;

namespace EFB.Controllers
{
    //[Route("[controller]")]
    public class ChartsController : Controller
    {
        private readonly ILogger<ChartsController> _logger;

        public ChartsController(ILogger<ChartsController> logger)
        {
            _logger = logger;
        }

        public async Task<IActionResult> Index(string ICAO)
        {
            UserModel user = HttpContext.Session.GetObject<UserModel>("User");
            if (user == null)
            {
                TempData["Error"] = "Must be logged in to view charts";
                return RedirectToAction("Index", "Home");
            }
            
            if(ICAO == null)
                return View();

            if (FormAuthenticator.ValidateICAOCode(ICAO))
            {
                var charts = await ChartModel.FetchAsync(ICAO);
                if (charts != null)
                {
                    ChartModel chartModel = new ChartModel(ICAO, charts);
                    //Save the current chart into user model for later access
                    user.CurrentCharts = chartModel;
                    HttpContext.Session.SetObject("User", user);
                    return RedirectToAction("ViewCharts");
                }
            }else
            {
                TempData["Error"] = "Invalid ICAO";
            }
            return View();
        }

        public IActionResult ViewCharts(string chart){
            UserModel user = HttpContext.Session.GetObject<UserModel>("User");
            if (user != null)
            {
                ViewChartModel charts = new ViewChartModel(user.CurrentCharts, chart);

                if (charts != null)
                {
                    return View("ViewCharts", charts);
                }
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index", "Home");
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View("Error!");
        }
    }
}