using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Engineer.Forms;
using Microsoft.Win32;

using Halo3Map;
using Halo3Map.Data;
using System.IO;
using Engineer.Librarys.Plugin_Converter;
using Engineer.Controls;

namespace Engineer.Forms
{
    /// <summary>
    /// Engineer experience starts here!
    /// </summary>
    public partial class Main : Form
    {
        /// <summary>
        /// Creates new instance of form1
        /// </summary>
        public Main()
        {
            //Load all form components
            InitializeComponent();
        }

        //Current version
        public static double CurrentVersion = 1.100;

        /// <summary>
        /// Load all our settings before the form is displayed
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {
            //Get app setting file directory
            AppSettings.settingsDirectory = Application.StartupPath;
            //Load settings file
            AppSettings.LoadSettings();

            //Load list of recently opened files
            Load_Recent_Files();

            if (AppSettings.Settings.ShowTipsAtStartup)
            {
                TipsDisplay tipsForm = new TipsDisplay();
                tipsForm.MdiParent = this;
                tipsForm.Show();
            }

            //Clean up from the last update
            Updating.PerformCleanup();

            //If Auto Update Checking is turned on
            if (AppSettings.Settings.AutoCheckForUpdates)
            {
                //Get time of last update check
                DateTime last; DateTime.TryParse(AppSettings.Settings.LastCheckedOn, out last);
                //Get time that it currently is
                DateTime now = DateTime.Now;
                //Get the timespan between the above to times
                TimeSpan span = now.Subtract(last);

                //Check how often user chose to check for updates
                switch (AppSettings.Settings.CheckEvery)
                {
                    //If check should be done everyday
                    case Settings.WhenToCheck.Day:
                        //And last update check was more than a day ago
                        if (span.Days >= 1)
                            //Perform Update Check
                            CheckForUpdate();
                        break;
                    case Settings.WhenToCheck.Week:
                        if (span.Days >= 7)
                            CheckForUpdate();
                        break;
                    case Settings.WhenToCheck.Month:
                        if (span.Days >= 31)
                            CheckForUpdate();
                        break;
                    case Settings.WhenToCheck.Year:
                        if (span.Days >= 365)
                            CheckForUpdate();
                        break;
                    case Settings.WhenToCheck.Startup:
                        CheckForUpdate();
                        break;
                }

            }

        }

        /// <summary>
        /// Checks if there is an update available
        /// </summary>
        private void CheckForUpdate()
        {

            Updating.UpdateInfo ui = Updating.GetUpdateInfo();
            if (Updating.isUpdateAvaiable(ui, CurrentVersion))
            {
                // if (MessageBox.Show("There is a update. Would you like to get it now?", "Update!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                //   new Update().ShowDialog();
                new NewUpdate(ui).ShowDialog();
            }
            else
            {
                MessageBox.Show("There is no update at this time.");
            }

            //Log when this update was checked
            AppSettings.Settings.LastCheckedOn = DateTime.Now.ToString();
            //Save it to the settings file
            AppSettings.SaveSettings();

        }
        /// <summary>
        /// Opens a map for editing
        /// </summary>
        private void openMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Create Open File Dialog
            OpenFileDialog ofd = new OpenFileDialog();
            //If user has a map folder set make that the intial directory to open
            if (AppSettings.Settings.MapFolder != "")
                ofd.InitialDirectory = AppSettings.Settings.MapFolder;
            //Only allow files with .map extension
            ofd.Filter = "Halo 3 Map File (*.map)|*.map";
            //Show Dialog and if ok is pressed continue
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //If the is not a map foler set in the settings file
                if (AppSettings.Settings.MapFolder == "")
                {
                    //Set map folder as the director this map was openend from
                    AppSettings.Settings.MapFolder = Path.GetDirectoryName(ofd.FileName) + "\\";
                    //Save settings file
                    AppSettings.SaveSettings();
                }
                //Create new Map Editor form using the selected filename
                Map_Editor ME = new Map_Editor(ofd.FileName);
                //Set parent form as form 1
                ME.MdiParent = this;
                //Forms title will be the filename of the open map
                ME.Text = ofd.FileName;
                //Show form
                ME.Show();
                //Update list of recently opened maps
                Update_Recent_Files(ofd.FileName);
            }
        }
        /// <summary>
        /// Updates recent file list with new map filename
        /// </summary>
        /// <param name="filename">Filename of map to add to list</param>
        public void Update_Recent_Files(string filename)
        {
            //Create new recent file item
            RecentFiles RF = new RecentFiles();
            //Set file path as path of the map to add
            RF.FilePath = filename;
            //Assume the map doesnt exist in the list yet
            bool exist = false;
            //Loop list to see if the map is already in the list
            foreach (RecentFiles rf in AppSettings.Settings.RecentFiles)
            {
                //If match is found set exist to true
                if (RF.FilePath == rf.FilePath) { exist = true; }
            }

            if (!exist)
            {
                //Add to recent files list in the settings file
                AppSettings.Settings.RecentFiles.Add(RF);

                // Add menu item.
                Add_Recent_File_To_Menu(AppSettings.Settings.RecentFiles.Count - 1);
            }

            while (AppSettings.Settings.RecentFiles.Count >= 6) // Max 5.
            {
                //Remove Oldest list item

                if (AppSettings.Settings.RecentFiles[0].MenuItem != null)
                    fileToolStripMenuItem.DropDownItems.Remove(AppSettings.Settings.RecentFiles[0].MenuItem);

                AppSettings.Settings.RecentFiles.RemoveAt(0);
            }

            //Save settings file
            AppSettings.SaveSettings();
        }
        /// <summary>
        /// Loads dropdown list of recent files
        /// </summary>
        public void Load_Recent_Files()
        {
            //If the are recent file entrys in the list
            if (AppSettings.Settings.RecentFiles.Count != 0)
            {
                //Loop through list
                for (int i = 0; i < AppSettings.Settings.RecentFiles.Count; i++)
                {
                    Add_Recent_File_To_Menu(i);
                }
            }
        }

        private void Add_Recent_File_To_Menu(int recentFileIndex)
        {
            //Create new toolstrip menu item
            ToolStripMenuItem tmi = new ToolStripMenuItem();
            //Set name as "RecentFile" + the list number we are on (Ex. "RecentFile4")
            tmi.Name = "RecentFile" + recentFileIndex;
            //Set text as the filepath of map
            tmi.Text = AppSettings.Settings.RecentFiles[recentFileIndex].FilePath;
            //Creat new click event so we can open the map on when its clicked
            tmi.Click += new EventHandler(tmi_Click);
            //Insert toolstripmenuitems into the file menu dropdownlist
            fileToolStripMenuItem.DropDownItems.Insert(2, tmi);

            // So we can keep track of the item.
            AppSettings.Settings.RecentFiles[recentFileIndex].MenuItem = tmi;

            //Male no recent files item invisible
            recentFilesToolStripMenuItem.Visible = false;
        }
        /// <summary>
        /// Click event: Opens a recent file using
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tmi_Click(object sender, EventArgs e)
        {
            //Create new map editor form using name of the clicked dropdown item
            Map_Editor ME = new Map_Editor(sender.ToString());
            //Set parent form as form1
            ME.MdiParent = this;
            //Forms title will be the name of the drop down button(map filename)
            ME.Text = sender.ToString();
            //Show form
            ME.Show();
        }
        /// <summary>
        /// Show the settings property grid
        /// </summary>
        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// Form closing event: Saves settings file when settings form is closed
        /// </summary>
        void settings_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Save settings
            AppSettings.SaveSettings();
        }
        /// <summary>
        /// TileHorizontal: Tiles open window Horizontally
        /// </summary>
        private void tileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }
        /// <summary>
        /// TileVertical: Tiles open window Vertically
        /// </summary>
        private void tileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }
        /// <summary>
        /// Cascade Click Event: Casacade all open windows
        /// </summary>
        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }
        /// <summary>
        /// Exit Click Event: Closes form
        /// </summary>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// CheckForUpdates Click Event: Checks for program update
        /// </summary>
        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckForUpdate();
        }
        /// <summary>
        /// About Click Event: Shows about form
        /// </summary>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Create new about form
            About about = new About();
            //Set parent as form1
            about.MdiParent = this;
            //Show form
            about.Show();
        }

        private void windowsToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
        {
            toolStripSeparator4.Visible = (this.MdiChildren.Length != 0);
        }

        private void restoreDefaultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Form to hold property grid
            Form settings = new Form();
            //Form needs to be able to adjust size to size of property grid
            settings.AutoSize = true;
            //Dont let the form be resized
            settings.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            //Set parent as form1
            settings.MdiParent = this;
            //Create property grid to hold setting values
            PropertyGrid pg = new PropertyGrid();
            //Dock it in the settings form
            pg.Dock = DockStyle.Fill;
            //Load PG with value of settings file
            pg.SelectedObject = AppSettings.Settings;
            //Create new form closing event
            settings.FormClosing += new FormClosingEventHandler(settings_FormClosing);
            //Add PG control to settings form
            settings.Controls.Add(pg);
            //Show settings form
            settings.Show();
        }

        private void clearSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AppSettings.ClearSettings();
        }

        private void pluginConverterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Converter cnv = new Converter();
            cnv.MdiParent = this;
            cnv.Show();
        }

        private void addressCalculatorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Engineer.Librarys.Offset_Calculator.Calculator calc = new Engineer.Librarys.Offset_Calculator.Calculator();
            calc.MdiParent = this;
            calc.Show();
        }
    }
}