using AppData;
using Newtonsoft.Json;
using NKC_SDK;
using System.IO;
using System.Web.Http;

namespace NKC_WF.Controllers
{
    public class BunkController : ApiController
    {
        #region Protected Fields

        /// <summary>
        /// COdice macchina (HARD CODED)
        /// </summary>
        protected string CodPost = "WRK001";

        /// <summary>
        /// oggetto static/singleton per fare chiamate sul datalayer
        /// </summary>
        protected DataLayer DLMan = new DataLayer();

        #endregion Protected Fields

        #region Public Methods

        /// <summary>
        /// Restituisce il FIRST BUNK da lavorare
        /// GET: api/Bunk
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ProdBunk Get()
        {
            ProdBunk answ = null;
            try
            {
                answ = ComLib.prodGetFirstBunk(CodPost);
            }
            catch
            { }
            return answ;
        }

        /// <summary>
        /// Ottengo NEXT BUNK
        /// GET: api/Bunk/2?showNext=true
        /// </summary>
        /// <param name="id"></param>
        /// <param name="showNext"></param>
        /// <returns></returns>
        [HttpGet]
        public ProdBunk Get(int id, bool showNext, string machine)
        {
            ProdBunk answ = null;
            CodPost = machine;
            try
            {
                if (showNext)
                {
                    answ = ComLib.prodGetNextBunk(id, CodPost);
                }
                else
                {
                    answ = ComLib.prodGetBunk(id);
                }
            }
            catch
            { }
            return answ;
        }

        /************************************
         * METODI PUT
         *
         * per abilitare è necessario agire sulla conf di IIS:
         *
         * - modificare il file applicationHost.config che si trova in C:\Windows\System32\inetsrv\config
         * - disinstallare webDav oppure commentare le righe
         *  <!-- <add name="WebDAVModule" /> -->
         *  <!-- <add name="WebDAVModule" image="%windir%\System32\inetsrv\webdav.dll" /> -->
         *  <!-- <add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" /> -->
         * - aggiungere PUT/DELETE a handler:
         *  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
         *  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
         *
         **************************************/

        /// <summary>
        /// Processa una chiamata POST per l'invio in blocco status BUNK
        /// POST: api/Bunk
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Post()
        {
            string answ = "";
            // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
            string content = "";
            System.Web.HttpContext.Current.Request.InputStream.Position = 0;
            using (var reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
            {
                content = reader.ReadToEnd();
            }
            //Rest
            System.Web.HttpContext.Current.Request.InputStream.Position = 0;
            // procedo a deserializzare in blocco l'oggetto...
            try
            {
                // deserializzo.
                ProdBunk currBunk = JsonConvert.DeserializeObject<ProdBunk>(content);
                // se non nullo...
                if (currBunk != null)
                {
                    foreach (var item in currBunk.SheetList)
                    {
                        // calcolo stsatus dalle date valide...

                        DLMan.taSHL.updateDate(item.SheetId, item.Printing.DtStart, item.Printing.DtEnd, item.Machining.DtStart, item.Machining.DtEnd, item.Unloading.DtStart, item.Unloading.DtEnd, (int)item.Status);
                        // SE machining completato --> status a LAVORATO!
                        if (item.Machining.DtEnd != null)
                        {
                            DLMan.taIL.updateSheetStatus(item.SheetId, 1, "PROD");
                        }
                    }
                    // segnalo avanzamento su redis x pagina unload
                    ComLib.advaceSheetRevByBunk(currBunk.BunkId);
                }
                answ = "OK";
            }
            catch
            {
                answ = "NO";
            }
            return answ;
        }

        /// <summary>
        /// Effettua la chiamata di update
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        // PUT: api/Bunk/5
        [HttpPut]
        public void Put(ProdBunk currBunk)
        {
            // NB. decodifico direttamente come oggetto, vedere qui:
            // https://weblog.west-wind.com/posts/2013/dec/13/accepting-raw-request-body-content-with-aspnet-web-api
            // https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

            // se non nullo...
            if (currBunk != null)
            {
                foreach (var item in currBunk.SheetList)
                {
                    DLMan.taSHL.updateDate(item.SheetId, item.Printing.DtStart, item.Printing.DtEnd, item.Machining.DtStart, item.Machining.DtEnd, item.Unloading.DtStart, item.Unloading.DtEnd, (int)item.Status);
                    // verifico SE SIA AVVENUTO CON SUCCESSO lo step di lavorazione...
                    if (item.Machining.Success)
                    {
                        // SE machining completato --> status a LAVORATO!
                        if (item.Machining.DtEnd != null)
                        {
                            DLMan.taIL.updateSheetStatus(item.SheetId, 1, "PROD");
                        }
                    }
                }
            }
            // INVALIDO eventuale valore BUNK in REDIS...
            ComLib.resetRedisBunkData(CodPost);
        }

        #endregion Public Methods
    }
}