using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using lkfxdok.c;
using LKFWSContracts;

namespace WebCoreDemo
{
    public class LKFSession
    {

        internal LKFContextWithData lkfContextWithData;

        static Dictionary<string, LKFSession> sessions = new Dictionary<string, LKFSession>();

        LKFSession(HttpContext context)
        {

        }

        public static LKFSession GetCurrent(HttpContext context)
        {
            var sessionId = context.Session.Id;
            LKFSession lkfSession;
            if (!sessions.TryGetValue(sessionId, out lkfSession))
            {
                lkfSession = new LKFSession(context);
                sessions.Add(sessionId, lkfSession);
            }
            return lkfSession;
        }

        private string[] ToStringArray(Exception ex)
        {
            var s = new List<String>();
            while (ex != null)
            {
                s.Add(ex.Message);
                ex = ex.InnerException;
            }

            var sa = new string[s.Count];
            s.CopyTo(sa);
            return sa;
        }

        public PrepareDataResponse Prepare(PrepareData data)
        {
            lkfContextWithData = new LKFContextWithData();

            int dataYear = data.dataYear;
            int modelYear = data.modelYear;

            if (dataYear == 0)
            {
                dataYear = modelYear;
            }
            else if (modelYear == 0)
            {
                modelYear = dataYear;
            }

            try
            {
                lkfContextWithData.Modelljahr = modelYear;
                lkfContextWithData.SetAbrechnungsPeriode(dataYear, 0, 0, LKFContextPeriode.Jahr, data.flags);
                return new PrepareDataResponse { success = true };
            }
            catch (Exception ex)
            {
                return new PrepareDataResponse { success = false, errors = ToStringArray(ex) };
            }
        }

        public ComputeResponse Compute (Compute computeRequest)
        {
            lkfContextWithData.PlausCheck();
            lkfContextWithData.Scoring();
            var ac = lkfContextWithData.AufenthaltCount;
            var ec = lkfContextWithData.ErrorCount;
            var wc = lkfContextWithData.WarningCount;
            var ic = lkfContextWithData.InfoCount;
            var p = lkfContextWithData.GetContextScoringValue(34);

            return new ComputeResponse { caseCount = ac, errorCount = ec, warningCount = wc, infoCount = ic, sumPoints = p };

        }
    }
}
