using AppData;
using SteamWare;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NKC_WF.site
{
    public partial class UpdMan : BasePage
    {
        protected DS_App.UpdManDataTable _tabPackages { get; set; } = new DS_App.UpdManDataTable();

        protected DS_App.UpdManDataTable tabPackages
        {
            get
            {
                DS_App.UpdManDataTable tabella = _tabPackages;
                if (tabella == null || tabella.Count == 0)
                {
                    tabella = DLMan.taUpdMan.GetData();
                }
                return tabella;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            DataLayer DLMan = new DataLayer();
            if (!Page.IsPostBack)
            {
                ((SiteContent)this.Master).showSearch = false;
            }
        }


        /// <summary>
        /// Eseguo download pacchetti secondo richeista
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtDownload_Click(object sender, EventArgs e)
        {
            // NOTA: da rivedere con basic AUTH x nexus... da cambiare metodi libreria steamwareLibs...
            // https://putridparrot.com/blog/downloading-a-file-from-url-using-basic-authentication/
            // https://www.codeproject.com/Articles/13485/Secure-File-Download-Using-Basic-Authentication
            // https://stackoverflow.com/questions/38798237/downloading-files-from-web-using-basic-url-authorization

            // dati da salvare in RESOURCE file...vedere progetto MHT Siemens
            // USER: SWDownloader
            // PWD: viaD@nte16

            LinkButton lnk = (LinkButton)sender;
            string caller = lnk.CommandArgument;
            string resultsMsg = "";
            // in base al caller scarico il file installazione richiesto...
            if (caller == null)
            {
                caller = "ALL";
            }
            // ora verifico COSA devo scaricare...
            if (!string.IsNullOrEmpty(updateUrl(caller)))
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                // se è ALL scarico tutti...
                if (caller == "ALL")
                {
                    int done = 0;

                    foreach (var item in tabPackages)
                    {
                        doDownload(caller, item);
                    }

                    stopWatch.Stop();
                    // calcolo elapsed time come TimeSpan value.
                    TimeSpan ts = stopWatch.Elapsed;
                    resultsMsg = $"OK: {done} Package downloaded, {ts.TotalSeconds:0.000} sec";
                }
                else
                {

                    var riga = tabPackages.FindByAppName(caller);
                    doDownload(caller, riga);
                    // calcolo elapsed time come TimeSpan value.
                    TimeSpan ts = stopWatch.Elapsed;
                    resultsMsg = $"OK: {caller} downloaded, {ts.TotalSeconds:0.000} sec | {updateUrl(caller)} --> {localDownloadPath(caller)}";
                }
            }
            // aggiorno messaggio
            lblOut.Text = resultsMsg;
        }

        private int doDownload(string caller, DS_App.UpdManRow riga)
        {
            int numDone = 0;
            // modalità DB...
            if (riga != null)
            {
                if (riga.IsAuth)
                {
                    updManAuth.downloadLatest(updateUrlAuth(riga.AppName), localDownloadPath(riga.LocalRepo), riga.PackName);
                    numDone++;
                }
                else
                {
                    UpdateMan.obj.downloadLatest(updateUrl(riga.AppName), localDownloadPath(riga.LocalRepo), riga.PackName);
                    numDone++;
                }
            }
            // modalità LEGACY...
            else
            {
                if (caller == "ALL")
                {
                    // scarico TUTTI...
                    numDone += updManAuth.downloadLatest(updateUrlAuth("NKC"), localDownloadPath("NKC"), "NKC");
                    numDone += UpdateMan.obj.downloadLatest(updateUrl("ZCODE"), localDownloadPath("ZCODE"), "ZCODE");

                    // versione IIS
                    //numDone += UpdateMan.obj.downloadLatest(updateUrl("NKC"), localDownloadPath("NKC"), "NKC");
                    //numDone += UpdateMan.obj.downloadLatest(updateUrl("ZCODE"), localDownloadPath("ZCODE"), "ZCODE");
                }
                else
                {
                    UpdateMan.obj.downloadLatest(updateUrl(caller), localDownloadPath(caller), caller);
                numDone++;
                }
            }
            return numDone;
        }

        public string Version(object package, object authUrl)
        {
            UpdateInfoEventArgs updArgs = new UpdateInfoEventArgs();
            string answ = "a.b.c.d";
            bool isAuth = false;
            bool.TryParse($"{authUrl}", out isAuth);
            // Recupero info...
            if (isAuth)
            {
                updArgs = updManAuth.getUpdateInfo(updateUrlAuth($"{package}"));
            }
            else
            {
                updArgs = UpdateMan.obj.getUpdateInfo(updateUrl($"{package}"));
            }
            if (updArgs.IsUpdateAvailable)
            {
                answ = $"{updArgs.CurrentVersion}";
            }
            else
            {
                answ = $"OK {updArgs.CurrentVersion}";
            }
            return answ;
        }

        /// <summary>
        /// Controller versioni e download autenticato
        /// </summary>
        protected UpdateMan updManAuth = new UpdateMan("SWDownloader", "viaD@nte16");

        /// <summary>
        /// URLK stringa di UPDATE...
        /// </summary>
        protected string updateUrl(string package)
        {
            string answ = "";
            var riga = tabPackages.FindByAppName(package);
            if (riga != null)
            {
                answ = riga.ManifestUrl;
            }
            else
            {
                answ = string.Format("http://seriate.steamware.net:8083/SWS/{0}/{1}/manifest.xml", package, memLayer.ML.CRS("appVers"));
            }
            return answ;
        }
        /// <summary>
        /// URL stringa di UPDATE su area che richiede Auth (nexus.steamware.net)...
        /// </summary>
        protected string updateUrlAuth(string package)
        {
            string answ = "";
            var riga = tabPackages.FindByAppName(package);
            if (riga != null)
            {
                answ = riga.ManifestUrl;
            }
            else
            {
                answ = string.Format("http://nexus.steamware.net/repository/SWS/{0}/{1}/LAST/{0}/{0}-.xml", package, memLayer.ML.CRS("appVers"));
            }
            return answ;
        }
        /// <summary>
        /// Path locale dove scaricare gli installer
        /// </summary>
        protected string localDownloadPath(string package)
        {
            return string.Format(@"{0}{1}\{2}", memLayer.ML.CRS("downloadPath"), package, memLayer.ML.CRS("appVers"));
        }
    }
}