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 ClipClop.User;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace ClipClop.View
{
    public partial class HistoryForm : ActiveForm
    {
        public ListBox.ObjectCollection History
        {
            get
            {
                return this.listBoxHistory.Items;
            }
        }

		public string ScriptFile	
		{
			get
			{
				if( comboBoxScriptFile.SelectedIndex == 0)
					return string.Empty;
				return comboBoxScriptFile.SelectedItem.ToString();
			}
		}


        public HistoryForm()
        {
            InitializeComponent();

            FormUtil.GeometryFromString(Properties.Settings.Default.WindowGeometryHistoryForm, this);

			splitContainer.Dock = DockStyle.Fill;
			listBoxHistory.Dock = DockStyle.Fill;
        }

        #region イベント

        public void HotkeyEventHandler_Active()
        {
            this.Open();
        }

        public void HotkeyEventHandler_DeleteHistory()
        {
            this.listBoxHistory.RemoveLast();
        }

        private void 先頭に移動ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listBoxHistory.MoveHead(false);
        }

        private void 改行を削除して先頭へToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listBoxHistory.MoveHead(true);
        }

        private void 削除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listBoxHistory.DeleteSelectedItem();
        }

        private void 全て削除toolStripMenuItem_Click(object sender, EventArgs e)
        {
            listBoxHistory.Clear();
            SetListContextMenuStripEnabled(false);
        }

        private void ファイルに保存toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listBoxHistory.SelectedIndex < 0)
                return;
            string s = listBoxHistory.SelectedItem.ToString();

            using (SaveFileDialog d = new SaveFileDialog())
            {
                d.DefaultExt = "txt";
                d.OverwritePrompt = true;
                d.InitialDirectory = string.IsNullOrEmpty(ClipClop.Properties.Settings.Default.InitialDirectoryTextFile) ?
                    string.Empty : ClipClop.Properties.Settings.Default.InitialDirectoryTextFile;
                d.FileName = Util.MakeFileName(s);
                d.Filter = "TEXTファイル(*.TXT)|*.TXT|すべてのファイル(*.*)|*.*";

                DialogResult ret = d.ShowDialog();
                if (ret != DialogResult.OK)
                    return;

                ClipClop.Properties.Settings.Default.InitialDirectoryTextFile = Path.GetDirectoryName(d.FileName);

                try
                {
                    using (StreamWriter sw = new StreamWriter(d.FileName, false, Encoding.UTF8))
                    {
                        sw.Write(s);
                        sw.Close();
                    }
                }
                catch (Exception ex)
                {
                    Util.ShowError(ex.Message);
                }
            }
        }

        private void listBoxHistory_SelectedIndexChanged(object sender, EventArgs e)
        {
            //操作メニューの有効無効更新
            if (listBoxHistory.SelectedIndex < 0)
                SetListContextMenuStripEnabled(false);
            else
                SetListContextMenuStripEnabled(true);

        }

		private void 編集toolStripMenuItem_Click(object sender, EventArgs e)
		{
			int index = listBoxHistory.SelectedIndex;
			if (index < 0)
				return;
			string s = listBoxHistory.SelectedItem.ToString();

			using (EditHistoryForm f = new EditHistoryForm())
			{
				f.Setup(this.Opacity, this.listBoxHistory.Font);
				f.HistoryString = s;

				DialogResult ret = f.ShowDialog();
				if (ret != DialogResult.OK)
					return;
				if (string.IsNullOrEmpty(f.HistoryString))
					return;

				if (index != 0)
				{
					listBoxHistory.Items.Insert(index, f.HistoryString);
					listBoxHistory.Items.RemoveAt(index + 1);
				}
				else
				{
					listBoxHistory.Items.RemoveAt(0);

					DataObject data = new DataObject();
					data.SetData(f.HistoryString);

					try
					{
						Clipboard.SetDataObject(data, true);
					}
					catch (System.Runtime.InteropServices.ExternalException)
					{
						//何もしない。
					}
				}
			}

		}

        #endregion

        public void Read(string path)
        {
            this.listBoxHistory.Read(path);
        }

        public void Save(string path)
        {
            this.listBoxHistory.Save(path);
        }

        public void Setup(bool alwaysTop, double opacity, Font f, int maxCout)
        {
            this.TopMost = alwaysTop;
            this.Opacity = opacity;


            this.listBoxHistory.Font = f;

            //履歴最大数設定
            listBoxHistory.SetMax(maxCout);
        }

        private void SetListContextMenuStripEnabled(bool enable)
        {
            foreach (ToolStripItem item in listContextMenuStrip.Items)
            {
                item.Enabled = enable;
            }
            listContextMenuStrip.Enabled = enable;
        }

        /// <summary>
        /// ダブルクリック等で開く
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Open_Click(object sender, MouseEventArgs e)
        {
            Open();
        }
        public void Open_Click(object sender, EventArgs e)
        {
            Open();
        }

		private void HistoryForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!base.CheckClosing(sender, e))
            {
                return;
            }

            Properties.Settings.Default.WindowGeometryHistoryForm = FormUtil.GeometryToString(this);
        }

		public void InsertHead(string text)
		{
			this.listBoxHistory.InsertHead(text);
		}


		public void SetupScriptFiles( string folder, string lastFilename)
		{
			comboBoxScriptFile.Items.Clear();

			comboBoxScriptFile.Items.Add(ClipClop.Properties.Resources.CmbNoScript);
			comboBoxScriptFile.SelectedIndex = 0;

			if (string.IsNullOrEmpty(folder))
				return;

			string[] files = Directory.GetFiles(folder, ClipClop.Properties.Settings.Default.ScriptFileExt);

			foreach (string f in files)
			{
				string fn = Path.GetFileName(f);

				int idx =  comboBoxScriptFile.Items.Add(fn);

				if (string.IsNullOrEmpty(lastFilename) == false &&
					string.Compare(fn, lastFilename, true) == 0)
				{
					comboBoxScriptFile.SelectedIndex = idx;
				}
			}
		}

    }
}
