﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FindSmoPolicy.Properties;

namespace FindSmoPolicy.DBF
{
    public partial class LoadDbf : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private static DateTime startTime;

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Application.AllKeys.Contains("dataContext") && CustomValidator1.IsValid)
            {
                lock (LogText)
                {
                    if (!IsLoadingDbf)
                    {
                        var callParam = new LoadDbfParams();
                        callParam.Context = new LoadDbfBackgroundContext();
                        callParam.DbfDir = Settings.Default.DbfDir;
                        var newTask = new Task(Run, callParam);
                        lblTime.Text = "Загрузка начата ...";
                        startTime = DateTime.Now;
                        LogText.Clear();
                        newTask.Start();
                    }
                    else
                        TextBox1.Text = @"Загрузка уже производится !!!";
                }
            }
        }

        public static List<string> LogText = new List<string>();
        public static HttpApplicationState application = null;
        public static bool IsLoadingDbf { get; set; }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            lock (LogText)
            {
                if (IsLoadingDbf)
                {
                    lblTime.Text = "Время " + DateTime.Now.Subtract(startTime).ToString(@"hh\:mm\:ss");
                }

                foreach (var newLine in LogText)
                {
                    var newRow = new TableRow();
                    newRow.Cells.Add(new TableCell());
                    newRow.Cells[0].Text = newLine;
                    Table1.Rows.Add(newRow);
                }

            }
        }

        protected void Run(object args)
        {
            lock (LogText)
                IsLoadingDbf = true;
            try
            {
                var policyContainer = (DataModelContainer)Application["dataContext"];
                policyContainer.RegisterEvent("Администратор", "Начата загрузка БД", "", "");
                policyContainer.LoadFromDbf(args);
                policyContainer.RegisterEvent("Администратор", "Закончена загрузка БД", "", "");
            }
            finally
            {
                lock (LogText)
                    IsLoadingDbf = false;
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = TextBox1.Text == Settings.Default.AdminPassword;
        }

    }

    public class LoadDbfParams
    {
        public IBackgroundContext Context;
        public string DbfDir;
    }


    public class LoadDbfBackgroundContext : IBackgroundContext
    {
        public void ReportProgress(string messageString, params object[] args)
        {
            lock (LoadDbf.LogText)
            {
                LoadDbf.LogText.Add(DateTime.Now.ToString() + " " + string.Format(messageString, args));
            }
        }

        public bool CancellationPending { get; private set; }
        public void ReportProgress()
        {
            
        }

        public void ProgressSeparator(char separatorChar = '*')
        {
            ReportProgress("".PadRight(80, separatorChar));
        }

        public void ReportError(string messageString, params object[] args)
        {
            ReportProgress(@"ОШИБКА: " + messageString, args);
        }

        public void Cancel()
        {
            
        }

        public event EventHandler<StringEventArgs> Progress;
    }
}