using System;
using System.Windows.Controls;

using SharpCompress.Archive;
using SharpCompress.Common;
using System.IO;
using System.Windows;

namespace Ocya_Launcher
{
    class Extract
    {
        public String FileName { get; set; }
        public String FilePath { get; set; }
        public ProgressBar Progress { get; set; }
        public Label Information { get; set; }
        public Boolean IsFinished;

        public void StartExtract()
        {
            using (var CurrentArchive = ArchiveFactory.Open(FilePath))
            {
                Int32 Completed = 0;
                Int32 Total = 0;

                foreach (var CurrentEntry in CurrentArchive.Entries) { if (!CurrentEntry.IsDirectory) { Total++; } }

                foreach (var CurrentEntry in CurrentArchive.Entries)
                {
                    Double CompletedDouble = (Double)Completed;
                    Double TotalDouble = (Double)Total;
                    Double ProgressDouble = (CompletedDouble / TotalDouble);
                    Int32 ProgressPercentage = (Int32)(ProgressDouble * 100);

                    if (!CurrentEntry.IsDirectory)
                    {
                        if (Progress != null) { Progress.Dispatcher.BeginInvoke((Action)(() => { Progress.Value = ProgressPercentage; })); }
                        if (Information != null) { Information.Dispatcher.BeginInvoke((Action)(() => { Information.Content = String.Format("Extracting {0}: {1}% [{2}/{3}] :: File: {4}", FileName, ProgressPercentage, Completed, Total, Path.GetFileName(CurrentEntry.FilePath)); })); }

                        CurrentEntry.WriteToDirectory(AppDomain.CurrentDomain.BaseDirectory, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                    }

                    Completed++;
                }
            }

            if (Progress != null) { Progress.Dispatcher.BeginInvoke((Action)(() => { Progress.Value = 100; })); }
            if (Information != null) { Information.Dispatcher.BeginInvoke((Action)(() => { Information.Content = String.Format("Extracted {0} Successfully", FileName); })); }

            IsFinished = true;
        }
    }
}
