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.IO;

namespace WinnyProtocolAnalyzer
{
    public partial class SettingsControl : Form
    {
        private Settings Settings;

        public SettingsControl(ref Settings Settings)
        {
            InitializeComponent();
            this.Settings = Settings;
        }

        private void ClusterWordText_TextChanged(object sender, EventArgs e)
        {
            if (Encoding.Default.GetByteCount(ClusterWordText.Text) > Property.ClusterWordMaxLength)
            {
                MessageBox.Show("クラスタワードは255文字(全角128文字)以下にする必要があります", "Winny Protocol Analyzer", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                ClusterWordText.Text = ClusterWordText.Text.Substring(0, ClusterWordText.Text.Length - 1);
                return;
            }

            ClusterWordCount.Text = Encoding.Default.GetByteCount(ClusterWordText.Text).ToString() + "/255";

            if (ClusterWordText.Text.Length > 0)
            {
                AddCluster.Enabled = true;
            }
            else
            {
                AddCluster.Enabled = false;
            }
        }

        private void ClusterWords_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ClusterWordsList.SelectedIndex >= 0)
            {
                RemoveCluster.Enabled = true;
            }
            else
            {
                RemoveCluster.Enabled = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog.ShowDialog();
            if (folderBrowserDialog.SelectedPath.Length > 0)
            {
                DataFolderPath.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void Settings_Load(object sender, EventArgs e)
        {
            this.Port.Text = Settings.Port.ToString();
            this.UPnPCheck.Checked = Settings.UPnP;
            this.LineSpeed.Text = Settings.LineSpeed.ToString();
            this.Connections.Value = Settings.Connections;
            this.ReverseResolution.Checked = Settings.ReverseResolution;
            this.ReverseResolutionOnlyForNode.Checked = Settings.ReverseResolutionOnlyForNode;
            this.ReverseResolutionOnlyForKey.Checked = Settings.ReverseResolutionOnlyForKey;

            foreach (Cluster cluster in Settings.Clusters)
            {
                this.ClusterWordsList.Items.Add(cluster.ClusterWord, cluster.Enable);
            }
            foreach (Keyword keyword in Settings.Keywords)
            {
                this.KeywordList.Items.Add(keyword.Keywords, keyword.Enable);
            }

            if (Directory.Exists(Settings.DataFolder))
            {
                this.DataFolderPath.Text = Settings.DataFolder;
            }
            else
            {
                this.DataFolderPath.Text = Environment.CurrentDirectory;
            }
        }

        private void Cancel_Button_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            try
            {
                int iPort = int.Parse(this.Port.Text);
                if (iPort < Property.PortMin && iPort > Property.PortMax)
                {
                    MessageBox.Show("不正なポート番号です", "Winny Protocol Analyzer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                float fLineSpeed = float.Parse(this.LineSpeed.Text);

                if (ClusterWordsList.CheckedItems.Count > Property.ClusterCount)
                {
                    MessageBox.Show("クラスタワードは3つ以上選択することはできません", "Winny Protocol Analyzer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(this.DataFolderPath.Text))
                {
                    MessageBox.Show("データフォルダが指定されていません", "Winny Protocol Analyzer", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Directory.Exists(this.DataFolderPath.Text))
                {
                    if (MessageBox.Show(string.Format("フォルダ: {0} は存在しません\r\n作成しますか？", this.DataFolderPath.Text), "Winny Protocol Analyzer", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                    else
                    {
                        Directory.CreateDirectory(this.DataFolderPath.Text);
                    }
                }

                Settings.Port = iPort;
                Settings.UPnP = this.UPnPCheck.Checked;
                Settings.LineSpeed = fLineSpeed;
                Settings.Connections = (int)this.Connections.Value;
                Settings.ReverseResolution = this.ReverseResolution.Checked;
                Settings.ReverseResolutionOnlyForNode = this.ReverseResolutionOnlyForNode.Checked;
                Settings.ReverseResolutionOnlyForKey = this.ReverseResolutionOnlyForKey.Checked;

                int i = 0;
                Settings.ClusterWords = new string[Property.ClusterCount] { "", "", "" };
                Settings.Clusters.Clear();
                foreach (string Item in this.ClusterWordsList.Items)
                {
                    bool Enable = this.ClusterWordsList.CheckedItems.Contains(Item);
                    Settings.Clusters.Add(new Cluster(Item, (Enable) ? true : false));
                    if (Enable)
                    {
                        Settings.ClusterWords[i++] = Item;
                    }
                }

                Settings.Keywords.Clear();
                foreach (string Item in this.KeywordList.Items)
                {
                    bool Enable = this.KeywordList.CheckedItems.Contains(Item);
                    Settings.Keywords.Add(new Keyword(Item, (Enable) ? true : false));
                }

                Settings.DataFolder = this.DataFolderPath.Text;

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "WinnyProtocolAnalyzer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void AddCluster_Click(object sender, EventArgs e)
        {
            foreach (string Item in this.ClusterWordsList.Items)
            {
                if (this.ClusterWordText.Text == Item)
                {
                    return;
                }
            }

            this.ClusterWordsList.Items.Add(this.ClusterWordText.Text, false);
        }

        private void RemoveCluster_Click(object sender, EventArgs e)
        {
            this.ClusterWordsList.Items.RemoveAt(this.ClusterWordsList.SelectedIndex);
        }

        private void KeywordText_TextChanged(object sender, EventArgs e)
        {
            if (Encoding.Default.GetByteCount(KeywordText.Text) > Property.ClusterWordMaxLength)
            {
                MessageBox.Show("キーワードは255文字(全角128文字)以下にする必要があります", "Winny Protocol Analyzer", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                KeywordText.Text = KeywordText.Text.Substring(0, KeywordText.Text.Length - 1);
                return;
            }

            KeywordCount.Text = Encoding.Default.GetByteCount(KeywordText.Text).ToString() + "/255";

            if (KeywordText.Text.Length > 0)
            {
                this.AddKeyword.Enabled = true;
            }
            else
            {
                this.AddKeyword.Enabled = false;
            }
        }

        private void KeywordList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (KeywordList.SelectedIndex >= 0)
            {
                this.RemoveKeyword.Enabled = true;
            }
            else
            {
                this.RemoveKeyword.Enabled = false;
            }
        }

        private void AddKeyword_Click(object sender, EventArgs e)
        {
            foreach (string Item in this.KeywordList.Items)
            {
                if (this.KeywordText.Text == Item)
                {
                    return;
                }
            }

            this.KeywordList.Items.Add(this.KeywordText.Text, true);
        }

        private void RemoveKeyword_Click(object sender, EventArgs e)
        {
            this.KeywordList.Items.RemoveAt(this.KeywordList.SelectedIndex);
        }

        private void ReverseResolution_CheckedChanged(object sender, EventArgs e)
        {
            if (!this.ReverseResolution.Checked)
            {
                this.ReverseResolutionOnlyForNode.Enabled = true;
                this.ReverseResolutionOnlyForKey.Enabled = true;
            }
            else
            {
                this.ReverseResolutionOnlyForNode.Enabled = false;
                this.ReverseResolutionOnlyForKey.Enabled = false;
            }
        }

        private void ReverseResolutionOnlyForKey_CheckedChanged(object sender, EventArgs e)
        {
            if (ReverseResolutionOnlyForKey.Checked)
            {
                if (MessageBox.Show("このオプションを有効にするとキー処理プロセスに時間が掛かり場合によってはアプリケーションが予期せぬ動作をする恐れがあります\r\nオプションを有効にしますか？", "Winny Protocol Analyzer", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    this.ReverseResolutionOnlyForKey.Checked = false;
                    return;
                }

                ReverseResolution.Enabled = false;
                ReverseResolutionOnlyForNode.Enabled = false;
            }
            else
            {
                ReverseResolution.Enabled = true;
                ReverseResolutionOnlyForNode.Enabled = true;
            }
        }

        private void ReverseResolutionOnlyForNode_CheckedChanged(object sender, EventArgs e)
        {
            if (ReverseResolutionOnlyForNode.Checked)
            {
                ReverseResolution.Enabled = false;
                ReverseResolutionOnlyForKey.Enabled = false;
            }
            else
            {
                ReverseResolution.Enabled = true;
                ReverseResolutionOnlyForKey.Enabled = true;
            }
        }
    }
}
