using AppData;
using SteamWare;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace NKC_WF.Controllers
{
    public class getMUCssController : ApiController
    {
        // GET api/getMUCssController
        public HttpResponseMessage Get()
        {
            string answ = $"{getCssByPost(0)}";
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(answ, Encoding.UTF8, "text/css")
            };
        }

        // GET api/getMUCssController/5
        public HttpResponseMessage Get(int id)
        {
            string answ = $"{getCssByPost(id)}";
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(answ, Encoding.UTF8, "text/css")
            };
        }
        /// <summary>
        /// Calcola CSS da postsazione
        /// </summary>
        /// <param name="answ"></param>
        /// <param name="_sheetID"></param>
        /// <returns></returns>
        private static string getCssByPost(int sheetID)
        {
            // var base
            string answ = "";
            string redKeyZero = $"{ComLib.machineUnloadArea(0)}:Css";
            if (sheetID > 0)
            {
                // TTL standard
                int dataCacheTTL = memLayer.ML.cdvi("cssCacheTTL");
                dataCacheTTL = dataCacheTTL <= 0 ? 60 : dataCacheTTL;
                // recupero da REDIS!
                string redKey = $"{ComLib.machineUnloadArea(sheetID)}:Css";
                // se vuoto scrivo VUOTO...
                if (memLayer.ML.redKeyPresent(redKey))
                {
                    answ = memLayer.ML.getRSV(redKey);
                }
                // RICALCOLO SOLO SE non trovo in REDIS (perché invalidato)
                if (string.IsNullOrEmpty(answ))
                {
                    // se vuoto lo calcolo...
                    answ = ComLib.getCurrentCss(sheetID);
                }
                // salvo ANCHE per foglio 0... per 5 minuti
                memLayer.ML.setRSV(redKeyZero, answ, 60 * 5);
            }
            else
            {
                // leggo ultimo...
                try
                {
                    answ = memLayer.ML.getRSV(redKeyZero);
                }
                catch
                { }
            }
            // restituisco css
            return answ;
        }

    }
}