using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace RMDEC
{
    public partial class projectSelector : Form
    {

        private List<Object> globalProjectList = new List<Object>();
        public projectSelector()
        {
            InitializeComponent();
        }

        private void onIndexingComplete()
        {
            this.Cursor = Cursors.Arrow;
        }

        private bool tryAddProject(string projectFile)
        {
            string relativeName = projectFile.Remove(0,projectDir.Text.Length + 1);
            string extension = Path.GetExtension(projectFile).ToLower();

            if (extension == ".json" || extension == ".js" || extension == ".png")
            {
                try
                {
                    MVProject proj = MVProject.ParseSystemJson(projectFile);
                    globalProjectList.Add(proj);
                    if(!proj.MZ)
                        projectList.Items.Add("[RMMV] - " + proj.GameTitle + " - " + relativeName);
                    else
                        projectList.Items.Add("[RMMZ] - " + proj.GameTitle + " - " + relativeName);
                    selectButton.Enabled = true;
                }
                catch (Exception) { return false; }
            }
            else if (extension == ".rgss3a") 
            {
                try
                {
                    VXAProject proj = VXAProject.ParseRgss3a(projectFile);
                    globalProjectList.Add(proj);
                    projectList.Items.Add("[RMVXA] - " + proj.GameTitle + " - " + relativeName);
                    selectButton.Enabled = true;
                }
                catch (Exception) { return false; }
            }

            return true;
        }
        private void updateProjectList(string projectDir)
        {
            if (Directory.Exists(projectDir))
            {

                this.Cursor = Cursors.WaitCursor;

                Thread indexProjects = new Thread(() =>
                {

                    IEnumerable fileList = Directory.EnumerateFiles(projectDir, "*", SearchOption.AllDirectories);

                    try
                    {
                        foreach (string fileEntry in fileList)
                        {
                            bool shouldBreak = false;
                            if (Path.GetFileName(fileEntry).ToLower() == "system.json" || Path.GetFileName(fileEntry).ToLower().StartsWith("rmmz_core") || Path.GetFileName(fileEntry).ToLower().StartsWith("rpg_core") || Path.GetFileName(fileEntry).ToLower().StartsWith("icon.png") || Path.GetExtension(fileEntry).ToLower() == ".rgss3a")
                            {
                                Invoke((Action)delegate
                                {
                                    shouldBreak = tryAddProject(fileEntry);
                                });
                            }
                            if (shouldBreak)
                                break;
                        }
                    }
                    catch (Exception) { };

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

                indexProjects.Start();
            }

        }
        
        private void clearProjectList()
        {
            globalProjectList.Clear();
            projectList.Items.Clear();
            selectButton.Enabled = false;
        }

        private void projectDir_TextChanged(object sender, EventArgs e)
        {
            clearProjectList();
            string newDir = projectDir.Text;
            updateProjectList(newDir);    
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            CommonOpenFileDialog folderDialog = new CommonOpenFileDialog();
            folderDialog.IsFolderPicker = true;

            if (folderDialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                projectDir.Text = folderDialog.FileName;
            }
        }

        private void selectButton_Click(object sender, EventArgs e)
        {
            int index = projectList.SelectedIndex;
            if(index >= 0)
            {
                object proj = globalProjectList[index];
                if(proj is MVProject)
                {
                    mvProjectToolset mvToolset = new mvProjectToolset((MVProject)globalProjectList[index]);
                    this.Hide();
                    mvToolset.Show();
                    mvToolset.FormClosing += MvToolset_FormClosing;
                }
                if(proj is VXAProject)
                {
                    vxaProjectToolset vxToolset = new vxaProjectToolset((VXAProject)globalProjectList[index]);
                    this.Hide();
                    vxToolset.Show();
                    vxToolset.FormClosing += VxToolset_FormClosing;
                }
            }
        }

        private void onChildFormClosed()
        {
            foreach (object proj in globalProjectList)
            {
                if (proj is VXAProject)
                {
                    VXAProject vxproj = (VXAProject)proj;
                    vxproj.Close();
                }
            }

            clearProjectList();
            updateProjectList(projectDir.Text);

            this.Show();
        }
        private void MvToolset_FormClosing(object sender, FormClosingEventArgs e)
        {
            onChildFormClosed();
        }

        private void VxToolset_FormClosing(object sender, FormClosingEventArgs e)
        {
            onChildFormClosed();
        }

        private void projectSelector_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
    }
}
