using Infrastructure.DataAccess;
using Infrastructure.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestCasePlanner.Infrastructure
{
    public class SelectedProject : ISelectedProject
    {
        private const string CookieName = "TestCasePlanner-SelectedProjectID";

        private readonly AppDbContext Context;

        public SelectedProject(AppDbContext context)
        {
            Context = context;
        }

        public SelectedProject() : this(new AppDbContext())
        {

        }

        public TestProject Project
        {
            get 
            {
                if (System.Web.HttpContext.Current.Items["ProjectID"] == null)
                {
                    if (HttpContext.Current.Request.Cookies[CookieName] == null)
                    {
                         return Context.TestProjects.First();
                    }
                    else
                    {
                        var projectID = HttpContext.Current.Request.Cookies[CookieName].Value;
                        var projectIDNum = Convert.ToInt32(projectID);
                        var currentProject = Context.TestProjects.Find(projectIDNum);
                        if (currentProject == null)
                        {
                            // TO DO - if there isnt any project in system
                            return null;
                        }
                        else
                        {
                            return currentProject;
                        }
                    }
                }
                else
                {
                    var projectID = System.Web.HttpContext.Current.Items["ProjectID"];
                    var projectIDNum = Convert.ToInt32(projectID);
                    return Context.TestProjects.Find(projectIDNum);
                }
            }
        }

        public void SetProject(int? projectID)
        {
            if (HttpContext.Current.Request.Cookies[CookieName] == null) // project selected for the first time
            {
                // create new cookie
                var projectIDCookie = new HttpCookie(CookieName, projectID.ToString());
                HttpContext.Current.Response.Cookies.Add(projectIDCookie);
            }
            else if (HttpContext.Current.Request.Cookies[CookieName].Value != projectID.ToString()) // project changed
            {
                // create new cookie with updated project ID
                var projectIDCookie = new HttpCookie(CookieName, projectID.ToString());
                HttpContext.Current.Response.Cookies.Set(projectIDCookie);
            }

            // set item for dropdown refresh
            System.Web.HttpContext.Current.Items["ProjectID"] = projectID.ToString();
        }
    }
}