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 DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;

namespace UniversalEditor.Tools
{
    public partial class toolSetEncoding : XtraForm
    {
        frmMain enc;
        public toolSetEncoding(frmMain main)
        {
            this.enc = main;
            InitializeComponent();
            PopulateEncodingList();
        }

        protected virtual void PopulateEncodingList(string filter = "")
        {
            lstEncoding.Items.Clear();
            foreach (EncodingInfo e in Encoding.GetEncodings().Where(e => e.Name.ToUpper().Contains(filter.ToUpper())))
            {
                lstEncoding.Items.Add(e.Name);
            }
            SelectCurrentEncoding();
        }

        protected void SelectCurrentEncoding()
        {
            string encoding = Program.eT;
            if (lstEncoding.Items.Contains(encoding))
                lstEncoding.SelectedItem = (encoding);
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstEncoding.SelectedItem == null)
                {
                    XtraMessageBox.Show("Please select an encoding type before continuing.");
                }
                else
                {
                    string selectedEncoding = lstEncoding.SelectedItem as string;
                    if (string.IsNullOrEmpty(selectedEncoding))
                    {
                        XtraMessageBox.Show("Please select an encoding type before continuing.");
                    }
                    Program.rK.SetValue("0", selectedEncoding);
                    Program.eT = selectedEncoding;
                    lstEncoding.SelectedItem = selectedEncoding;
                    enc.SQLStatus.Caption = String.Format("Encoding has been set to {0}. This tool will now read and write in {0}.", selectedEncoding);
                    //Close();
                }
            }
            catch (Exception ex)
            {
                enc.SQLStatus.Caption = ("An error occured trying to change the encoding. " + ex.Message);
            }
        }

        private void tbSearchText_TextChanged(object sender, EventArgs e)
        {
            PopulateEncodingList(tbSearchText.Text);
        }

        private void btnDefault_Click(object sender, EventArgs e)
        {
            Program.rK.SetValue("0", "iso-8859-1");
            Program.eT = "iso-8859-1";
            lstEncoding.SelectedItem = "iso-8859-1";
            lstEncoding.SelectedIndex = lstEncoding.SelectedIndex;
            enc.SQLStatus.Caption = "Encoding has been set to iso-8859-1. SHN Editor will now read and write in iso-8859-1.";
        }
    }
}
