using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using static System.Windows.Forms.ListBox;

namespace RMDEC
{
    public partial class vxaProjectToolset : Form
    {
        public VXAProject vxProject;

        public vxaProjectToolset(VXAProject proj)
        {
            vxProject = proj;
            InitializeComponent();
        }

        
        private void onIndexThreadComplete()
        {
            processingText.Text = "Waiting";
            processingText.BackColor = Color.Red;

            decryptSelected.Enabled = true;

            makeVXA.Enabled = true;
            makeVXA.Enabled = true;

            processingBar.Style = ProgressBarStyle.Continuous;

            this.Cursor = Cursors.Arrow;
        }
        private void indexFiles()
        {
            processingText.Text = "Indexing";
            processingText.BackColor = Color.Yellow;
            processingBar.Style = ProgressBarStyle.Marquee;
            this.Cursor = Cursors.WaitCursor;

            //Index Encrypted Files
            Thread indexFiles = new Thread(() =>
            {

                vxProject.PopulateFileList();
                foreach (string file in vxProject.FileList)
                {
                    string fileExtension = Path.GetExtension(file);
                    string realPath = Path.Combine(vxProject.FilePath, file);


                    Invoke((Action)delegate
                    {
                        encryptedFileList.Items.Add("[" + fileExtension.ToUpper().TrimStart('.') + "] " + file);
                    });

                    if (File.Exists(realPath))
                    {
                        Invoke((Action)delegate
                        {
                            decryptedFileList.Items.Add("[" + fileExtension.ToUpper().TrimStart('.') + "] " + file);
                        });
                    }
                }
                
                Invoke((Action)delegate
                {
                    onIndexThreadComplete();
                });
                
            });
            indexFiles.Start();

           
        }
        private void VXAProjectToolset_Load(object sender, EventArgs e)
        {
            updateTitle();
            indexFiles();
        }

        private void updateTitle()
        {
            this.Text = "RMDec - [RMVXA] " + vxProject.GameTitle + " - " + vxProject.FilePath;
        }
        


        
        private void decryptSelected_Click(object sender, EventArgs e)
        {
            SelectedIndexCollection itemList = encryptedFileList.SelectedIndices;
            int itemCount = itemList.Count;

            if (itemCount < 1)
            {
                return;
            }

            int item = 0;

            processingBar.Style = ProgressBarStyle.Continuous;
            processingBar.Maximum = itemCount;

            processingText.BackColor = Color.Yellow;
            
            decryptSelected.Enabled = false;

            makeVXA.Enabled = false;
            
            Thread decryptFilesThread = new Thread(() =>
            {
                for(int i = 0; i < itemCount; i++)
                { 

                    Invoke((Action)delegate
                    {   
                        item = itemList[i];
                        processingText.Text = "Decrypting " + i.ToString() + "/" + itemCount.ToString();
                    });



                    string fileName = (Path.Combine(vxProject.FilePath, vxProject.FileList[item]));

                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                    FileStream Decrypted = File.OpenWrite(fileName);

                    vxProject.DecryptFile(item, Decrypted);
                    
                    Decrypted.Close();
                    
                    Invoke((Action)delegate
                    {
                        string encEntry = encryptedFileList.Items[i].ToString();
                        if (!decryptedFileList.Items.Contains(encEntry))
                        {
                            decryptedFileList.Items.Add(encEntry);
                        }

                        processingBar.Value = i;
                    });

                } 

                Invoke((Action)delegate
                {
                    decryptSelected.Enabled = true;
                    makeVXA.Enabled = true;
                    processingText.BackColor = Color.Green;
                    processingText.Text = "Decrypted " + itemCount.ToString() + " files!";
                });
            });

            decryptFilesThread.Start(); 
        }

        private void onMakeVxaComplete()
        {
            string rpgProject = Path.Combine(vxProject.FilePath, vxProject.ExeName+".rvproj2");
            string rpgEncryptedArchive = Path.Combine(vxProject.FilePath, vxProject.ExeName + ".rgss3a");
            File.WriteAllText(rpgProject, "RPGVXAce 1.00");
            
            if(File.Exists(rpgEncryptedArchive))
            {
                vxProject.Close();
                File.Move(rpgEncryptedArchive, rpgEncryptedArchive+".delete-me");
            }

            processingText.BackColor = Color.Green;
            processingText.Text = "Game Decrypted!";

            decryptSelected.Enabled = true;
            makeVXA.Enabled = true;

            Process.Start(vxProject.FilePath+"\\");
        }
        private void makeVXA_Click(object sender, EventArgs e)
        {
            int itemCount = vxProject.FileList.Count;

            //Decrypt Everything
            if (itemCount > 0)
            {
                processingBar.Style = ProgressBarStyle.Continuous;
                processingBar.Maximum = itemCount;

                processingText.BackColor = Color.Yellow;
                
                decryptSelected.Enabled = false;

                makeVXA.Enabled = false;
                makeVXA.Enabled = false;

                Thread decryptFilesThread = new Thread(() =>
                {
                   
                    for (int i = 0; i < itemCount; i++)
                    {
                        Invoke((Action)delegate
                        {
                            processingText.Text = "Decrypting " + i.ToString() + "/" + itemCount.ToString();
                        });


                        string fileName = (Path.Combine(vxProject.FilePath, vxProject.FileList[i]));

                        Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        FileStream Decrypted = File.OpenWrite(fileName);
                        vxProject.DecryptFile(i, Decrypted);
                        Decrypted.Close();
                        
                        Invoke((Action)delegate
                        {
                            string encEntry = encryptedFileList.Items[0].ToString();
                            if (!decryptedFileList.Items.Contains(encEntry))
                            {
                                decryptedFileList.Items.Add(encEntry);
                            }
                            encryptedFileList.Items.Remove(encEntry);
                            
                            processingBar.Value = i;
                        });
                    }


                    
                    Invoke((Action)delegate
                    {
                        onMakeVxaComplete();
                    });

                    

                });
                decryptFilesThread.Start();
            }
            else
            {
                onMakeVxaComplete();
            }
        }


    }
}
