using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using Microsoft.Win32;
using System.Diagnostics;
using DevExpress.XtraTab;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors;
using DevExpress.XtraTab.ViewInfo;
using DevExpress.XtraGrid.Columns;
using System.Data.OleDb;
using System.Globalization;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Helpers;
using UniversalEditor.Tools;
using UniversalEditor.Classes;

namespace UniversalEditor
{
    public partial class frmMain : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public bool UnSaved = false;
        private ShineTable OpenTable;
        private List<GridControl> LoadedGrids;
        public EncryptionType Encryption = EncryptionType.Default;

        public frmMain()
        {
            InitializeComponent();
        }

        void checkForParams()
        {
            string[] args = Environment.GetCommandLineArgs();

            if (args.Length == 1) return;
            string filePath = args[1];
        }

        // file open handler
        private void OpenButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenFileDialog o = new OpenFileDialog();
            o.Title = "Select SHN File";
            o.Filter = "SHN File (*.shn)|*.shn|Text File (*.txt)|*.txt";
            if (o.ShowDialog() == DialogResult.OK)
            {
                if (o.FileName.EndsWith(".shn"))
                {
                    InitFile(o.FileName);
                }
                else if (o.FileName.EndsWith(".txt"))
                {
                    DialogResult result = XtraMessageBox.Show("Is this file a table?", "Exine Games Editor", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        try
                        {
                            InitTable(o.FileName);
                        }
                        catch
                        {
                            InitText(o.FileName);
                        }
                    }
                    else
                    {
                        InitText(o.FileName);
                    }
                }
            }          
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            if (Environment.GetCommandLineArgs().Length > 1) { InitFile(Environment.GetCommandLineArgs()[1]); }

            SkinHelper.InitSkinPopupMenu(Skins);

            if (File.Exists(@"back.up"))
            {
                BackupBtn.Checked = true;
            }
            else
            {
                BackupBtn.Checked = false;
            }

            bool isAso = FileAssociation.AssociationCheck(".shn", "SHN Tool");
            FileAso.Checked = isAso;

            if (!isAso)
            {
                DialogResult result = XtraMessageBox.Show("Do you want to associate this tool with SHN files?", "SHN", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes) CreateAssociation();
            }

            setRegistryInfo();
            this.Text = "Exine Games Editor v" + Application.ProductVersion;
            checkForParams();
            SQLStatus.Caption = "Ready";
        }

        void CreateAssociation()
        {
            string[] OpenWithList = new string[] { "notepad.exe", "wordpad.exe" };
            FileAssociation.AssociationCreation(".shn", "SHN Tool", "application/myfile", OpenWithList, true, "SHN Editor");
        }

        private void setRegistryInfo()
        {
            try
            {
                Program.eT = Registry.CurrentUser.OpenSubKey("Software\\" + Program.assemblyName + "\\Encoding").GetValue("0").ToString();
            }
            catch (NullReferenceException)
            {
                Program.rK.SetValue("0", "ISO-8859-1");
                Program.eT = Registry.CurrentUser.OpenSubKey("Software\\" + Program.assemblyName + "\\Encoding").GetValue("0").ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred trying to get encoding type: " + ex.Message);
            }
        }

        private void InitTable (string FilePath)
        {
            try
            {
                LoadedGrids = new List<GridControl>();

                OpenTable = new ShineTable();
                OpenTable.Open(FilePath);

                foreach (Table CurrentTable in OpenTable.Tables)
                {
                    XtraTabPage p = FileTabs.TabPages.Add(CurrentTable.Name);

                    DataGrid g = new DataGrid(this);
                    g.TopLevel = false;
                    g.Visible = true;
                    ((GridControl)g.Controls[0]).DataSource = CurrentTable.Content;
                    g.Dock = DockStyle.Fill;

                    p.Controls.Add(g);
                    p.Tag = FilePath;

                    LoadedGrids.Add((GridControl)g.Controls[0]);

                    FileTabs.SelectedTabPage = p;
                }
            }
            catch (Exception e)
            {
                InitText(FilePath);
            }
        }

        private GridControl GetActiveTable()
        {
            GridControl ActivatedTable = null;

            foreach (GridControl CurrentGrid in this.LoadedGrids)
            {
                if (CurrentGrid.Parent != FileTabs.SelectedTabPage) { continue; }

                ActivatedTable = CurrentGrid;
            }

            return ActivatedTable;
        }

        void InitFile(string Filename, bool NewFile = false)
        {
            if (NewFile == false)
            {
                if (!File.Exists(Filename)) return;
                if (Path.GetFileName(Filename) == "QuestData.shn")
                {
                    MessageBox.Show("Please use iQuest as this application cannot view this file.");
                    return;
                }
                if (!(Filename.ToLower().EndsWith(".shn"))) //other file handling
                {
                    SHNFile file = new SHNFile();
                    file.LoadMe(Encryption, Filename);
                    return;
                }
            }
            try
            {
                XtraTabPage p;
                SHNFile ifile;

                if (NewFile == true)
                {
                    ifile = new SHNFile();
                    ifile.CreateDefaultLayout();                   
                    p = FileTabs.TabPages.Add(Filename);
                }
                else
                {
                    p = FileTabs.TabPages.Add(Path.GetFileName(Filename));
                    ifile = new SHNFile(Filename, Encryption);
                }
                DataGrid g = new DataGrid(this);
                p.Padding = new System.Windows.Forms.Padding(5);
                p.Tag = ((GridControl)g.Controls[0]);
                ((GridControl)g.Controls[0]).Tag = ifile;

                ((GridControl)g.Controls[0]).DataSource = ifile.table;

                g.TopLevel = false;
                g.Dock = DockStyle.Fill;
                g.Visible = true;
                p.Controls.Add(g);
                foreach (GridColumn column in ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).Columns)
                    column.Caption = column.FieldName;
                FileTabs.SelectedTabPage = p;
            }
            catch (Exception e)
            {
                SQLStatus.Caption = e.Message;
            }
        }

        public SHNFile file
        {
            get
            {
                try { return (SHNFile)dataGrid.Tag; }
                catch { /*MessageBox.Show("No file found");*/ return null; }
            }
            set
            {
                try { dataGrid.Tag = value; }
                catch { }
            }
        }

        public GridControl dataGrid
        {
            get
            {
                try { return (GridControl)FileTabs.SelectedTabPage.Tag; }
                catch { return null; }
            }
            set
            {
                FileTabs.SelectedTabPage.Tag = value;
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // check if a file is not saved
            foreach (XtraTabPage p in FileTabs.TabPages)
            {
                if (p.Text.Contains("*"))
                {
                    UnSaved = true;
                }
            }
            if (UnSaved == true)
            {
                DialogResult r = XtraMessageBox.Show("Ignore unsaved changes? All changes will be lost.", "Universal Editor", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (r == DialogResult.No)
                {
                    e.Cancel = true;
                }
                else
                {
                    e.Cancel = false;
                }
            }
        }

        private void NewButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveFileDialog s = new SaveFileDialog();
            s.Title = "Select file destination";
            s.Filter = "SHN File (*.shn)|*.shn|Text File (*.txt)|*.txt";

            if (s.ShowDialog() == DialogResult.OK)
            {
                if (s.FileName.Contains(".shn"))
                {
                    InitFile(Path.GetFileName(s.FileName), true);
                    SaveTo(s.FileName);
                }
                
                if (s.FileName.Contains(".txt"))
                {
                    InitText(s.FileName, true);
                }
            }
        }

        public void InitText(string FileName, bool IsNewFile = false)
        {
            XtraTabPage p = FileTabs.TabPages.Add(Path.GetFileName(FileName));
            TextEditor t = new TextEditor(this);
            t.TopLevel = false;
            t.Dock = DockStyle.Fill;
            t.Visible = true;

            if (IsNewFile)
            {
                File.WriteAllText(FileName, "");
            }

            t.richEditControl1.Document.LoadDocument(FileName, DevExpress.XtraRichEdit.DocumentFormat.PlainText);
            
            p.Tag = FileName;
            p.Padding = new System.Windows.Forms.Padding(5);
            p.Controls.Add(t);

            FileTabs.SelectedTabPage = p;
            string text = FileTabs.SelectedTabPage.Text;
            string Saved = text.Replace("*", String.Empty);
            FileTabs.SelectedTabPage.Text = Saved;
        }

        public void SaveTo(string FileName)
        {
            //if (File.Exists(FileName)) { File.Delete(FileName); }
            for (int i = 0; i < (((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.MainView).Columns.Count); i++)
            {
                file.displayToReal.Add(((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.MainView).Columns[i].VisibleIndex, i); //lists all displayed
            }
            bool suc = file.Save(Encryption, FileName);
            file.displayToReal.Clear();
            if (!suc)
            {
                //File.Delete(FileName);
                SQLStatus.Caption = "Could not save file(s).";
            }
            else
                SQLStatus.Caption = "File(s) saved!";
                string text = FileTabs.SelectedTabPage.Text;
                string Saved = text.Replace("*", String.Empty);
                FileTabs.SelectedTabPage.Text = Saved;
        
            file.displayToReal.Clear();
        }

        private void SaveButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            if (BackupBtn.Checked == true)
            {
                if (FileTabs.SelectedTabPage.Tag.ToString().Contains(".txt"))
                {
                    if (File.Exists(FileTabs.SelectedTabPage.Tag.ToString() + ".bck"))
                    {
                        File.Delete(FileTabs.SelectedTabPage.Tag.ToString() + ".bck");
                    }
                    if (OpenTable != null)
                    {
                        try
                        {
                            OpenTable.Save(OpenTable.FilePath);
                        }
                        catch
                        {
                            SQLStatus.Caption = "Could not save table.";
                        }
                    }
                    else
                    {
                        File.Move(FileTabs.SelectedTabPage.Tag.ToString(), FileTabs.SelectedTabPage.Tag.ToString() + ".bck");
                        ((DevExpress.XtraRichEdit.RichEditControl)((TextEditor)FileTabs.SelectedTabPage.Controls[0]).Controls[0]).Document.SaveDocument(FileTabs.SelectedTabPage.Tag.ToString(), DevExpress.XtraRichEdit.DocumentFormat.PlainText);
                    }
                    SQLStatus.Caption = "File(s) saved!";
                    string text = FileTabs.SelectedTabPage.Text;
                    string Saved = text.Replace("*", String.Empty);
                    FileTabs.SelectedTabPage.Text = Saved;
                }
                else
                {
                    if (File.Exists(file.Path + ".bck"))
                    {
                        File.Delete(file.Path + ".bck");
                    }
                    File.Move(file.Path, file.Path + ".bck");
                    SaveTo(file.Path);
                }
            }
            else
            {
                if (FileTabs.SelectedTabPage.Tag.ToString().Contains(".txt"))
                {
                    ((DevExpress.XtraRichEdit.RichEditControl)((TextEditor)FileTabs.SelectedTabPage.Controls[0]).Controls[0]).Document.SaveDocument(FileTabs.SelectedTabPage.Tag.ToString(), DevExpress.XtraRichEdit.DocumentFormat.PlainText);
                    SQLStatus.Caption = "File(s) saved!";
                    string text = FileTabs.SelectedTabPage.Text;
                    string Saved = text.Replace("*", String.Empty);
                    FileTabs.SelectedTabPage.Text = Saved;
                }
                else
                {
                    SaveTo(file.Path);
                }
            }         
        }

        private void FileTabs_CloseButtonClick(object sender, EventArgs e)
        {
            ClosePageButtonEventArgs arg = e as ClosePageButtonEventArgs;
            FileTabs.SelectedTabPage = (XtraTabPage)arg.Page;

            if (FileTabs.SelectedTabPage != null)
            {
                if (FileTabs.SelectedTabPage.Text.Contains("*"))
                {
                    DialogResult d = XtraMessageBox.Show("Do you want to save your changes?", "Universal Editor", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (d == DialogResult.Yes)
                    {
                        if (arg.Page.Text.Contains(".shn"))
                        {
                            SaveTo(file.Path);
                        }
                        if (arg.Page.Text.Contains(".txt"))
                        {
                            if (OpenTable != null)
                            {
                                try
                                {
                                    OpenTable.Save(OpenTable.FilePath);
                                }
                                catch
                                {
                                    SQLStatus.Caption = "Could not save table.";
                                }
                            }
                            else
                            {
                                ((DevExpress.XtraRichEdit.RichEditControl)((TextEditor)FileTabs.SelectedTabPage.Controls[0]).Controls[0]).Document.SaveDocument(FileTabs.SelectedTabPage.Tag.ToString(), DevExpress.XtraRichEdit.DocumentFormat.PlainText);
                            }
                        }
                        string t = arg.Page.Text;
                        string n = t.Replace("*", String.Empty);
                        ((XtraTabPage)arg.Page).Text = n;
                        (arg.Page as XtraTabPage).PageVisible = false;
                    }
                    else
                    {
                        string t = arg.Page.Text;
                        string n = t.Replace("*", String.Empty);
                        ((XtraTabPage)arg.Page).Text = n;
                        (arg.Page as XtraTabPage).PageVisible = false;
                    }
                }
                else
                {
                    (arg.Page as XtraTabPage).PageVisible = false;
                }
            }
            else
            {
                (arg.Page as XtraTabPage).PageVisible = false;
            }
        }

        private void SAButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            SaveFileDialog s = new SaveFileDialog();
            s.Title = "Select file destination";
            s.Filter = "SHN File (*.shn)|*.shn|Text File (*.txt)|*.txt";

            if (s.ShowDialog() == DialogResult.OK)
            {
                if (FileTabs.SelectedTabPage.Tag.ToString().Contains(".txt"))
                {
                    if (BackupBtn.Checked == true)
                    {
                        if (File.Exists(s.FileName))
                        {
                            if (File.Exists(s.FileName + ".bck"))
                            {
                                File.Delete(s.FileName + ".bck");
                            }
                            File.Move(s.FileName, s.FileName + ".bck");
                        }
                        if (OpenTable != null)
                        {
                            try
                            {
                                OpenTable.Save(s.FileName);
                            }
                            catch
                            {
                                SQLStatus.Caption = "Could not save table.";
                            }
                        }
                        else
                        {
                            ((DevExpress.XtraRichEdit.RichEditControl)((TextEditor)FileTabs.SelectedTabPage.Controls[0]).Controls[0]).Document.SaveDocument(s.FileName, DevExpress.XtraRichEdit.DocumentFormat.PlainText);
                        }
                        SQLStatus.Caption = "File(s) saved!";
                        string text = FileTabs.SelectedTabPage.Text;
                        string Saved = text.Replace("*", String.Empty);
                        FileTabs.SelectedTabPage.Text = Saved;
                    }
                }
                else
                {
                    if (BackupBtn.Checked == true)
                    {
                        if (File.Exists(s.FileName))
                        {
                            if (File.Exists(s.FileName + ".bck"))
                            {
                                File.Delete(s.FileName + ".bck");
                            }
                            File.Move(s.FileName, s.FileName + ".bck");
                        }

                        SaveTo(s.FileName);
                    }
                    else
                    {
                        SaveTo(s.FileName);
                    }
                }
            }
        }

        private void SAllButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            foreach (XtraTabPage p in FileTabs.TabPages)
            {
                FileTabs.SelectedTabPage = p;

                if (FileTabs.SelectedTabPage.Tag.ToString().Contains(".txt"))
                {
                    if (BackupBtn.Checked == true)
                    {
                        if (File.Exists(FileTabs.SelectedTabPage.Tag.ToString() + ".bck"))
                        {
                            File.Delete(FileTabs.SelectedTabPage.Tag.ToString() + ".bck");
                        }
                        if (OpenTable != null)
                        {
                            try
                            {
                                OpenTable.Save(OpenTable.FilePath);
                            }
                            catch
                            {
                                SQLStatus.Caption = "Could not save table.";
                            }
                        }
                        else
                        {
                            File.Move(FileTabs.SelectedTabPage.Tag.ToString(), FileTabs.SelectedTabPage.Tag.ToString() + ".bck");
                            ((DevExpress.XtraRichEdit.RichEditControl)((TextEditor)FileTabs.SelectedTabPage.Controls[0]).Controls[0]).Document.SaveDocument(FileTabs.SelectedTabPage.Tag.ToString(), DevExpress.XtraRichEdit.DocumentFormat.PlainText);
                        }
                        SQLStatus.Caption = "File(s) saved!";
                        string text = FileTabs.SelectedTabPage.Text;
                        string Saved = text.Replace("*", String.Empty);
                        FileTabs.SelectedTabPage.Text = Saved;
                    }
                    else
                    {
                        ((DevExpress.XtraRichEdit.RichEditControl)((TextEditor)FileTabs.SelectedTabPage.Controls[0]).Controls[0]).Document.SaveDocument(FileTabs.SelectedTabPage.Tag.ToString(), DevExpress.XtraRichEdit.DocumentFormat.PlainText);
                        SQLStatus.Caption = "File(s) saved!";
                        string text = FileTabs.SelectedTabPage.Text;
                        string Saved = text.Replace("*", String.Empty);
                        FileTabs.SelectedTabPage.Text = Saved;
                    }
                }
                else
                {
                    if (BackupBtn.Checked == true)
                    {
                        if (File.Exists(file.Path + ".bck"))
                        {
                            File.Delete(file.Path + ".bck");
                        }
                        File.Move(file.Path, file.Path + ".bck");
                        SaveTo(file.Path);
                    }
                    else
                    {
                        SaveTo(file.Path);
                    }
                }
            }
        }

        private void ECSV_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            SaveFileDialog s = new SaveFileDialog();
            s.Title = "Select export destination";
            s.Filter = "CSV File (*.csv)|*.csv";

            if (s.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    file.exportCVS(s.FileName);
                    SQLStatus.Caption = "File exported successfully!";
                }
                catch (Exception ex)
                {
                    SQLStatus.Caption = ex.Message;
                }
            }           
        }

        private void SearchButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).IsFindPanelVisible == true)
            {
                ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).HideFindPanel();
            }
            else
            {
                ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).ShowFindPanel();
            }           
        }

        private void CCreate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {         
            if (FileTabs.TabPages.Count < 1) return;
            columnCreate c = new columnCreate(this);
            c.init();
            c.ShowDialog();
        }

        private void CDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            columnDeletion d = new columnDeletion(this);
            d.init();
            d.ShowDialog();
        }

        private void CRename_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            columnRename r = new columnRename(this);
            r.init();
            r.ShowDialog();
        }

        private void CMult_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            columnMultiply m = new columnMultiply(this);
            m.init();
            m.ShowDialog();
        }

        public object maxID;

        private void RCreate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            if (((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).Columns["ID"] != null)
            {
                maxID = ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).GetRowCellValue(((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).RowCount - 1, "ID");
            }
            ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).AddNewRow();
            string t = FileTabs.SelectedTabPage.Text;
            string n = t.Replace("*", String.Empty);
            FileTabs.SelectedTabPage.Text = n;
            FileTabs.SelectedTabPage.Text = FileTabs.SelectedTabPage.Text + "*";
        }

        private void CBulk_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            columnBulkEdit b = new columnBulkEdit(this);
            b.init();
            b.ShowDialog();
        }

        private void CDiv_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            columnDivide d = new columnDivide(this);
            d.init();
            d.ShowDialog();
        }

        string ClipboardData
        {
            get
            {
                IDataObject iData = Clipboard.GetDataObject();
                if (iData == null) return "";

                if (iData.GetDataPresent(DataFormats.Text))
                    return (string)iData.GetData(DataFormats.Text);
                return "";
            }
            set { Clipboard.SetDataObject(value); }
        }

        private void RCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).CopyToClipboard();
            SQLStatus.Caption = "Row(s) copied to clipboard";
        }

        private void RPaste_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            string[] data = ClipboardData.Split('\n');
            if (data.Length < 1) return;
            foreach (string row in data)
            {
                try
                {
                    AddRow(row);
                    ((DevExpress.XtraGrid.Views.Grid.GridView)dataGrid.Views[0]).MoveLast();
                }
                catch
                {
                    SQLStatus.Caption = "Invalid format.";
                    return;
                }
            }
            string t = FileTabs.SelectedTabPage.Text;
            string n = t.Replace("*", String.Empty);
            FileTabs.SelectedTabPage.Text = n;
            FileTabs.SelectedTabPage.Text = FileTabs.SelectedTabPage.Text + "*";
            SQLStatus.Caption = "Row(s) pasted from clipboard";
        }

        void AddRow(string data)
        {
            if (data == string.Empty) return;
            string[] rowData = data.Split(new char[] { '\r', '\x09' });
            DataRow newRow = file.table.NewRow();
            for (int i = 0; i < rowData.Length; i++)
            {
                if (i >= file.table.Columns.Count) break;
                newRow[i] = rowData[i];
            }
            file.table.Rows.Add(newRow);
        }

        private void RFilter_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            rowFilter f = new rowFilter(this);
            f.init();
            f.ShowDialog();
        }

        private void RReplace_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            rowReplace r = new rowReplace(this);
            r.init();
            r.ShowDialog();
        }

        private void RTally_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            rowTally t = new rowTally(this);
            t.ShowDialog();
        }

        private void EXML_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            SaveFileDialog s = new SaveFileDialog();
            s.Title = "Select export destination";
            s.Filter = "XML File (*.xml)|*.xml";

            if (s.ShowDialog() == DialogResult.OK)
            {
                file.table.TableName = Path.GetFileName(s.FileName);
                file.table.WriteXml(s.FileName);
            }
        }

        private void ICSV_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenFileDialog o = new OpenFileDialog();
            o.Title = "Select CSV File";
            o.Filter = "Comma Separated File (*.csv)|*.csv";

            if (o.ShowDialog() == DialogResult.OK)
            {
                
            }
        }


        static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
        {
            string header = isFirstRowHeader ? "Yes" : "No";

            string pathOnly = Path.GetDirectoryName(path);
            string fileName = Path.GetFileName(path);

            string sql = @"SELECT * FROM [" + fileName + "]";

            using (OleDbConnection connection = new OleDbConnection(
                      @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
                      ";Extended Properties=\"Text;HDR=" + header + "\""))
            using (OleDbCommand command = new OleDbCommand(sql, connection))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
            {
                DataTable dataTable = new DataTable();
                dataTable.Locale = CultureInfo.CurrentCulture;
                adapter.Fill(dataTable);
                return dataTable;
            }
        }

        private void HeaderInfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            editHeaderInfo h = new editHeaderInfo(this);
            h.ShowDialog();
        }

        private void EXPEditor_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            if (!file.Path.EndsWith("MobInfoServer.shn"))
            {
                SQLStatus.Caption = ("Please open MobInfoServer.shn first!");
                return;
            }
            ExpEditor editor = new ExpEditor(this);
            editor.ShowDialog();
        }

        private void ItemEditor_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            else
            {
                if (FileTabs.SelectedTabPage.Text.ToString() != "ItemInfo.shn")
                {
                    SQLStatus.Caption = ("Please open ItemInfo.shn first.");
                    return;
                }
                else
                {
                    ItemEditor editor = new ItemEditor(this);
                    editor.ShowDialog();
                }
            }
        }

        private void TranslatorButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FileTabs.TabPages.Count < 1) return;
            Translator t = new Translator(this);
            t.ShowDialog();
        }

        private void FileAso_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (FileAso.Checked == false)
                {
                    FileAssociation.AssociationDeletion(".shn", "SHN Tool");
                    SQLStatus.Caption = "File association deleted!";
                }
                else
                {
                    CreateAssociation();
                    SQLStatus.Caption = "File association created!";
                }
            }
            catch (Exception ex)
            {
                SQLStatus.Caption = "An error occured: " + ex.Message;
            }
        }

        private void EncodingBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            toolSetEncoding enc = new toolSetEncoding(this);
            enc.ShowDialog();
        }

        private void BackupBtn_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (BackupBtn.Checked)
            {
                File.WriteAllText(@"back.up", "true");
            }
            else
            {
                if (File.Exists(@"back.up"))
                {
                    File.Delete(@"back.up");
                }
            }
        }

        private void FileTabs_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            try
            {
                if (FileTabs.TabPages == null)
                {
                    return;
                }
                if (!FileTabs.SelectedTabPage.Text.Contains(".shn"))
                {
                    ToolsPage.Visible = false;
                }
                else
                {
                    ToolsPage.Visible = true;
                }
            }
            catch
            {
                return;
            }
        }

        private void btnEncryption_ItemClick(object sender, ItemClickEventArgs e)
        {
            toolSetEncryption enc = new toolSetEncryption(this);
            enc.ShowDialog();
        }
    }
}
