using CommonLang.File;
using MPQ.FileSystem;
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;
using System.Windows.Forms;

namespace ToolsMPQ
{
    public partial class FormUnarchive : Form
    {
        private FileInfo mpq_file;
        private MPQFileSystem mpq_fs;
        public FormUnarchive(FileInfo mpq)
        {
            InitializeComponent();
            this.mpq_file = mpq;
            this.mpq_fs = new MPQFileSystem();
            this.mpq_fs.load(mpq_file.FullName);
            Thread t = new Thread(run_extract);
            t.Start();
        }

        private bool is_done = false;
        private Exception error;
        private string efile;
        private int max = 100;
        private int cur = 0;
        private void run_extract()
        {
            try
            {
                List<MPQFileEntry> entries = mpq_fs.listEntrys();
                max = entries.Count;
                foreach (MPQFileEntry e in entries)
                {
                    efile = e.Key;
                    byte[] data = mpq_fs.getEntryData(e);
                    FileInfo save = new FileInfo(mpq_file.DirectoryName + "\\" + mpq_file.Name.Substring(0, mpq_file.Name.Length - mpq_file.Extension.Length) + "\\" + e.Key);
                    CFiles.createFile(save);
                    File.WriteAllBytes(save.FullName, data);
                    cur++;
                }
            }
            catch (Exception err)
            {
                error = err;
            }
            finally
            {
                is_done = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (error != null)
            {
                MessageBox.Show(error.Message);
            }
            progressBar1.Maximum = max;
            progressBar1.Value = cur;
            label1.Text = efile;
            if (is_done)
            {
                this.Close();
            }
        }
    }
}