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

namespace MicronSync.Components.Forms
{
    public partial class DirSizeCalculatorPrompt : Form
    {
        public DirSizeCalculatorPrompt()
        {
            InitializeComponent();
        }

        BackgroundWorker bw = new BackgroundWorker();
        public string TargetDirectory;
        public double Result = 0;
        private bool canClose;

        #region Worker

        private void FinishCalculation(object sender, RunWorkerCompletedEventArgs e)
        {
            Close();
        }

        private void StartCalculation(object sender, DoWorkEventArgs e)
        {
            double result = 0;

            string[] allFiles = Directory.GetFiles(TargetDirectory, "*.*", SearchOption.AllDirectories);
            foreach (var file in allFiles)
            {
                if (!bw.CancellationPending)
                {
                    FileInfo info = new FileInfo(file);
                    result += info.Length;
                }
                else
                    result = 0;
            }

            using (CommonIO _cio = new CommonIO())
                Result = _cio.ConvertBytesToMB(result);

            canClose = true;
        }

        #endregion

        #region UI

        private void DirSizeCalculatorPrompt_Load(object sender, EventArgs e)
        {
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(StartCalculation);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FinishCalculation);
            bw.RunWorkerAsync();
        }

        private void DirSizeCalculatorPrompt_FormClosing(object sender, FormClosingEventArgs e)
        {
            bw.Dispose();
            GC.Collect();

            if (!canClose)
                e.Cancel = true;
            else
                e.Cancel = false;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            bw.CancelAsync();
        }

        #endregion
    }
}
