// Copyright (C) 2003, 2004 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2005, 2007, 2008, 2010 panacoran <panacoran@users.sourceforge.jp>
// Copyright (C) 2012 Daisuke Arai <darai@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: MainForm.cs 438 2012-06-22 16:54:17Z darai $

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Protra.Lib;
using Protra.Lib.Config;
using Protra.Lib.Data;
using PtSim.Dialogs;

namespace PtSim
{
    /// <summary>
    /// メインフォーム
    /// </summary>
    public partial class MainForm : Form
    {
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            // 設定ファイルをロードする。
            (GlobalEnv.PtSimConfig = new PtSimConfig()).Load();
            (GlobalEnv.UpdateConfig = new UpdateConfig()).Load();
            (GlobalEnv.BrandData = new Protra.Lib.Data.BrandData()).Load();
            (GlobalEnv.BrandListConfig = new BrandListConfig()).Load();

            ListViewSystemInit();
            dateTimePickerMin.Value = DateTime.Now.AddMonths(-1); //履歴の開始を1ヶ月前に設定する。

            // 実行できないボタンを無効にする。
            List<SystemAndTarget> list = GetCheckedSystemAndTarget();
            EnableButtons(list.Count > 0);
            deleteLogToolStripMenuItem.Enabled = list.Count > 0;
            deleteSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
            upSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
            downSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;

            GlobalEnv.UpdateConfig.SetWatcher(null);
            GlobalEnv.BrandListConfig.SetWatcher(null);

            // 先頭のカラムでソートされる状態にする。
            listViewProfitBrand.SetSortColumn(0);
            listViewTrade.SetSortColumn(0);
            listViewHistory.SetSortColumn(0);
        }

        /// <summary>
        /// メインエントリポイント
        /// </summary>
        [STAThread]
        public static void Main()
        {
            if (Win32API.ProcessAlreadyExists())
                return;
            Application.EnableVisualStyles();
            Application.Run(new MainForm());
        }

        /// <summary>
        /// 売買システムリストビューに、設定ファイルの情報を反映します。
        /// </summary>
        private void ListViewSystemInit()
        {
            int i = 0;
            foreach (var sat in GlobalEnv.PtSimConfig.SystemAndTargetList)
            {
                this.listViewSystem.Items.Add(new ListViewItem(new string[]{
                        System.IO.Path.GetFileNameWithoutExtension(sat.SystemFileName),
                        sat.BrandListName,
                        sat.Mode == 0 ? "日足" : "週足",
                        i.ToString() // SystemAndTargetListのインデックスを記憶
                    }));
                if (sat.Checked)
                    this.listViewSystem.Items[i].Checked = true;
                i++;
            }
        }

        /// <summary>
        /// チェックされている売買システムのリストを取得します。
        /// </summary>
        /// <returns>チェックされている売買システムのリスト</returns>
        private List<SystemAndTarget> GetCheckedSystemAndTarget()
        {
            List<SystemAndTarget> list = new List<SystemAndTarget>();
            foreach (var sat in GlobalEnv.PtSimConfig.SystemAndTargetList)
            {
                if (sat.Checked)
                    list.Add(sat);
            }
            return list;
        }

        private void EnableButtons(bool enable)
        {
            buttonExecute.Enabled = enable;
            buttonHistory.Enabled = enable;
            buttonCalc.Enabled = enable;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigWrite();
        }

        /// <summary>
        /// 設定ファイルを書き込む。
        /// </summary>
        private void ConfigWrite()
        {
            var p = GlobalEnv.PtSimConfig;
            p.Save();
        }

        private void buttonExecute_Click(object sender, EventArgs e)
        {
            List<SystemAndTarget> list = GetCheckedSystemAndTarget();
            // 選択された売買システムを表示するサンプル
            foreach (var sat in list)
            {
                textBoxExecute.AppendText(sat.SystemFileName + " ");
                textBoxExecute.AppendText(sat.BrandListName + " ");
                textBoxExecute.AppendText(sat.Mode + "\n");
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void addSystemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectSystemAndTargetDialog f = new SelectSystemAndTargetDialog();
            if (f.ShowDialog() == DialogResult.OK)
            {
                SystemAndTarget sat = f.SystemAndTarget;
                if (sat != null)
                {
                    if (GlobalEnv.PtSimConfig.SystemAndTargetList.Contains(sat))
                        return;
                    GlobalEnv.PtSimConfig.SystemAndTargetList.Add(sat);
                    // 売買システムリストビューへの追加
                    this.listViewSystem.Items.Add(new ListViewItem(new string[]{
                            System.IO.Path.GetFileNameWithoutExtension(sat.SystemFileName),
                            sat.BrandListName,
                            sat.Mode == 0 ? "日足" : "週足",
                            (GlobalEnv.PtSimConfig.SystemAndTargetList.Count - 1).ToString() // SystemAndTargetListのインデックスを記憶
                        }));
                }
            }
        }

        private void upSystemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listViewSystem.SelectedItems.Count == 0)
                return;

            ListViewItem item = this.listViewSystem.SelectedItems[0];
            int i = int.Parse(item.SubItems[3].Text);
            if (i > 0)
            {
                GlobalEnv.PtSimConfig.SystemAndTargetList.Reverse(i - 1, 2);
                this.listViewSystem.Items.Clear();
                ListViewSystemInit();
                this.listViewSystem.Items[i - 1].Selected = true;
            }
        }

        private void downSystemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listViewSystem.SelectedItems.Count == 0)
                return;

            ListViewItem item = this.listViewSystem.SelectedItems[0];
            int i = int.Parse(item.SubItems[3].Text);
            if (i < GlobalEnv.PtSimConfig.SystemAndTargetList.Count - 1)
            {
                GlobalEnv.PtSimConfig.SystemAndTargetList.Reverse(i, 2);
                this.listViewSystem.Items.Clear();
                ListViewSystemInit();
                this.listViewSystem.Items[i + 1].Selected = true;
            }
        }

        private void deleteSystemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listViewSystem.SelectedItems.Count == 0)
                return;

            DialogResult r = MessageBox.Show("選択されたアイテムを削除します。よろしいですか。\n※チェックされたアイテムではありません。", "確認", MessageBoxButtons.YesNo);
            if (r != DialogResult.Yes)
                return;

            ListViewItem item = this.listViewSystem.SelectedItems[0];
            GlobalEnv.PtSimConfig.SystemAndTargetList.RemoveAt(int.Parse(item.SubItems[3].Text));
            this.listViewSystem.Items.Clear();
            ListViewSystemInit();

            deleteSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
            upSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
            downSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
        }

        private void listViewSystem_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            SystemAndTarget sat = GlobalEnv.PtSimConfig.SystemAndTargetList[int.Parse(this.listViewSystem.Items[e.Index].SubItems[3].Text)];
            sat.Checked = (e.NewValue == CheckState.Checked);

            List<SystemAndTarget> list = GetCheckedSystemAndTarget();
            EnableButtons(list.Count > 0);
            deleteLogToolStripMenuItem.Enabled = list.Count > 0;
        }

        private void listViewSystem_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            deleteSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
            upSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
            downSystemToolStripMenuItem.Enabled = this.listViewSystem.SelectedItems.Count > 0;
        }
    }
}
