using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sownloader
{
    public partial class UpdateWindow : Form
    {
        private const string sownloader_url = "https://www.sownloader.com/Sownloader.zip";
        private string zipPath = Path.Combine(Application.StartupPath, "Sownloader.zip");

        FileHandler.INIClass inifile;

        HttpWebRequest _request;
        IAsyncResult _responseAsyncResult;
        public UpdateWindow(string latestVersion)
        {
            InitializeComponent();
            lblVersionOld.Text = Application.ProductVersion;
            lblVersionNew.Text = latestVersion;
            inifile = new FileHandler.INIClass();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            lblStatus.Visible = true;
            pgbDownload.Visible = true;

            HttpWebRequest dbUpdateRequest = (HttpWebRequest)WebRequest.Create("https://sownloader.com/functions/updater.php?action=updateDatabase&version=" + lblVersionNew.Text + "&code=ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff");
            dbUpdateRequest.UserAgent = "Sownloader/" + Application.ProductVersion;
            WebResponse dbUpdateResponse = dbUpdateRequest.GetResponse();
            Stream dataStream = dbUpdateResponse.GetResponseStream();
            StreamReader readerDBupdate = new StreamReader(dataStream);
            string responseFromServer = readerDBupdate.ReadLine();
            readerDBupdate.Close();
            dataStream.Close();

            _request = (HttpWebRequest)WebRequest.Create(sownloader_url);
            _request.UserAgent = "Sownloader " + Application.ProductVersion;
            _responseAsyncResult = _request.BeginGetResponse(ResponseCallback, null);
        }

        private void ResponseCallback(object state)
        {
            var response = _request.EndGetResponse(_responseAsyncResult) as HttpWebResponse;
            long contentLength = response.ContentLength;
            if (contentLength == -1)
            {
                // You'll have to figure this one out.
            }
            Stream responseStream = response.GetResponseStream();
            GetContentWithProgressReporting(responseStream, contentLength);
            response.Close();

            
        }

        private byte[] GetContentWithProgressReporting(Stream responseStream, long contentLength)
        {
            UpdateProgressBar(0);
            
            // Allocate space for the content
            var data = new byte[contentLength];
            int currentIndex = 0;
            int bytesReceived = 0;
            var buffer = new byte[256];
            do
            {
                bytesReceived = responseStream.Read(buffer, 0, 256);
                Array.Copy(buffer, 0, data, currentIndex, bytesReceived);
                currentIndex += bytesReceived;
                // Report percentage
                double percentage = (double)currentIndex / contentLength;
                UpdateProgressBar((int)(percentage * 100));
            } while (currentIndex < contentLength);

            UpdateProgressBar(100);

            File.WriteAllBytes(zipPath, data);
            try
            {
                Process updateProcess = new Process();
                updateProcess.StartInfo.FileName = Path.Combine(Application.StartupPath, "update.bat");
                updateProcess.StartInfo.Arguments = "\"" + AppDomain.CurrentDomain.BaseDirectory + "\" \"" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sownloader.zip") + "\"";
                updateProcess.Start();
            }
            catch (Exception)
            {

                throw;
            }
            return data;
        }

        private void UpdateProgressBar(int percentage)
        {
            // If on a worker thread, marshal the call to the UI thread
            if (pgbDownload.InvokeRequired)
            {
                pgbDownload.Invoke(new Action<int>(UpdateProgressBar), percentage);
            }
            else
            {
                pgbDownload.Value = percentage;
            }
        }

        private void btnLater_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void UpdateWindow_Load(object sender, EventArgs e)
        {

        }

        private void btnSkip_Click(object sender, EventArgs e)
        {
            inifile.UpdateSkipVersion(lblVersionNew.Text);
            this.Close();
        }

       
    }
}
