// Copyright (C) 2003, 2004 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2005, 2007, 2008 panacoran <panacoran@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,v 1.28 2008-08-09 07:07:38 panacoran Exp $

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml;
using PtSim.Dialogs;
using Protra.Lib;
using Protra.Lib.Config;
using Protra.Lib.Controls;
using Protra.Lib.Db;

namespace PtSim
{
    /// <summary>
    /// アプリケーションのメインフォームです。
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        /// <summary>
        /// 最前面のウィンドウをセットします。
        /// </summary>
        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow(int hwnd);

        private ConfigFile configFile = new ConfigFile("ptsimenv");

        private System.Windows.Forms.MainMenu mainMenu;
        private System.Windows.Forms.MenuItem menuItemLog;
        private System.Windows.Forms.MenuItem menuItemLogDelete;
        private System.Windows.Forms.MenuItem menuItemLogAllDelete;
        private System.Windows.Forms.MenuItem menuItemBrandList;
        private System.Windows.Forms.MenuItem menuItemBrandListEdit;
        private System.Windows.Forms.MenuItem menuItemHelp;
        private System.Windows.Forms.MenuItem menuItemMan;
        private System.Windows.Forms.MenuItem menuItemVersion;
        private System.Windows.Forms.Panel panelLeft;
        private System.Windows.Forms.Panel panelSelect;
        private System.Windows.Forms.Label labelMode;
        private System.Windows.Forms.Label labelBrandList;
        private System.Windows.Forms.RadioButton radioButtonDaily;
        private System.Windows.Forms.RadioButton radioButtonWeekly;
        private System.Windows.Forms.ComboBox comboBoxBrandList;
        private System.Windows.Forms.Splitter splitterLeft;
        private System.Windows.Forms.TabControl tabControl;
        private System.Windows.Forms.TabPage tabPageExecute;
        private System.Windows.Forms.TabPage tabPagePerformance;
        private System.Windows.Forms.TabPage tabPageHistory;
        private System.Windows.Forms.ImageList imageListTab;
        private Protra.Lib.Controls.PtFileTreeView ptFileTreeView;
        private Protra.Lib.Controls.SimulateTextBox simulateTextBox;
        private System.Windows.Forms.Button buttonExecute;
        private System.Windows.Forms.ProgressBar progressBarExecute;
        private System.Windows.Forms.TabControl tabControlPerformance;
        private System.Windows.Forms.TabPage tabPagePerformanceSummery;
        private System.Windows.Forms.TabPage tabPagePerformanceProfitGraph;
        private System.Windows.Forms.RichTextBox richTextBoxPerformanceSummery;
        private PtSim.Controls.ProfitGraphBox profitGraphBox;
        private System.Windows.Forms.Button buttonPerformance;
        private System.Windows.Forms.ProgressBar progressBarPerformance;
        private PtSim.Controls.ListViewEx listViewHistory;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryDate;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryCode;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryName;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryPrice;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryNumber;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryOrder;
        private System.Windows.Forms.Label labelDateRange;
        private System.Windows.Forms.Button buttonHistory;
        private System.Windows.Forms.DateTimePicker dateTimePickerHistoryDateMax;
        private System.Windows.Forms.DateTimePicker dateTimePickerHistoryDateMin;
        private System.Windows.Forms.ContextMenu historyContextMenu;
        private System.Windows.Forms.MenuItem copyHistory;
        private BackgroundWorker backgroundWorkerPerformance;
        private BackgroundWorker backgroundWorkerExecute;
        private System.ComponentModel.IContainer components;

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainForm()
        {
            //
            // Windows フォーム デザイナ サポートに必要です。
            //
            InitializeComponent();

            //
            // TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
            //
        }

        /// <summary>
        /// 使用されているリソースに後処理を実行します。
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// デザイナ サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディタで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
            this.menuItemLog = new System.Windows.Forms.MenuItem();
            this.menuItemLogDelete = new System.Windows.Forms.MenuItem();
            this.menuItemLogAllDelete = new System.Windows.Forms.MenuItem();
            this.menuItemBrandList = new System.Windows.Forms.MenuItem();
            this.menuItemBrandListEdit = new System.Windows.Forms.MenuItem();
            this.menuItemHelp = new System.Windows.Forms.MenuItem();
            this.menuItemMan = new System.Windows.Forms.MenuItem();
            this.menuItemVersion = new System.Windows.Forms.MenuItem();
            this.panelLeft = new System.Windows.Forms.Panel();
            this.ptFileTreeView = new Protra.Lib.Controls.PtFileTreeView();
            this.panelSelect = new System.Windows.Forms.Panel();
            this.labelMode = new System.Windows.Forms.Label();
            this.labelBrandList = new System.Windows.Forms.Label();
            this.comboBoxBrandList = new System.Windows.Forms.ComboBox();
            this.radioButtonDaily = new System.Windows.Forms.RadioButton();
            this.radioButtonWeekly = new System.Windows.Forms.RadioButton();
            this.splitterLeft = new System.Windows.Forms.Splitter();
            this.tabControl = new System.Windows.Forms.TabControl();
            this.tabPageExecute = new System.Windows.Forms.TabPage();
            this.progressBarExecute = new System.Windows.Forms.ProgressBar();
            this.buttonExecute = new System.Windows.Forms.Button();
            this.simulateTextBox = new Protra.Lib.Controls.SimulateTextBox();
            this.tabPagePerformance = new System.Windows.Forms.TabPage();
            this.progressBarPerformance = new System.Windows.Forms.ProgressBar();
            this.buttonPerformance = new System.Windows.Forms.Button();
            this.tabControlPerformance = new System.Windows.Forms.TabControl();
            this.tabPagePerformanceSummery = new System.Windows.Forms.TabPage();
            this.richTextBoxPerformanceSummery = new System.Windows.Forms.RichTextBox();
            this.tabPagePerformanceProfitGraph = new System.Windows.Forms.TabPage();
            this.profitGraphBox = new PtSim.Controls.ProfitGraphBox();
            this.tabPageHistory = new System.Windows.Forms.TabPage();
            this.buttonHistory = new System.Windows.Forms.Button();
            this.labelDateRange = new System.Windows.Forms.Label();
            this.dateTimePickerHistoryDateMax = new System.Windows.Forms.DateTimePicker();
            this.dateTimePickerHistoryDateMin = new System.Windows.Forms.DateTimePicker();
            this.listViewHistory = new PtSim.Controls.ListViewEx();
            this.columnHeaderHistoryDate = new System.Windows.Forms.ColumnHeader();
            this.columnHeaderHistoryCode = new System.Windows.Forms.ColumnHeader();
            this.columnHeaderHistoryName = new System.Windows.Forms.ColumnHeader();
            this.columnHeaderHistoryPrice = new System.Windows.Forms.ColumnHeader();
            this.columnHeaderHistoryNumber = new System.Windows.Forms.ColumnHeader();
            this.columnHeaderHistoryOrder = new System.Windows.Forms.ColumnHeader();
            this.historyContextMenu = new System.Windows.Forms.ContextMenu();
            this.copyHistory = new System.Windows.Forms.MenuItem();
            this.imageListTab = new System.Windows.Forms.ImageList(this.components);
            this.backgroundWorkerPerformance = new System.ComponentModel.BackgroundWorker();
            this.backgroundWorkerExecute = new System.ComponentModel.BackgroundWorker();
            this.panelLeft.SuspendLayout();
            this.panelSelect.SuspendLayout();
            this.tabControl.SuspendLayout();
            this.tabPageExecute.SuspendLayout();
            this.tabPagePerformance.SuspendLayout();
            this.tabControlPerformance.SuspendLayout();
            this.tabPagePerformanceSummery.SuspendLayout();
            this.tabPagePerformanceProfitGraph.SuspendLayout();
            this.tabPageHistory.SuspendLayout();
            this.SuspendLayout();
            // 
            // mainMenu
            // 
            this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemLog,
            this.menuItemBrandList,
            this.menuItemHelp});
            // 
            // menuItemLog
            // 
            this.menuItemLog.Index = 0;
            this.menuItemLog.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemLogDelete,
            this.menuItemLogAllDelete});
            this.menuItemLog.Text = "システムログ(&L)";
            // 
            // menuItemLogDelete
            // 
            this.menuItemLogDelete.Index = 0;
            this.menuItemLogDelete.Shortcut = System.Windows.Forms.Shortcut.Del;
            this.menuItemLogDelete.Text = "削除(&D)";
            this.menuItemLogDelete.Click += new System.EventHandler(this.menuItemLogDelete_Click);
            // 
            // menuItemLogAllDelete
            // 
            this.menuItemLogAllDelete.Index = 1;
            this.menuItemLogAllDelete.Text = "全システムログを削除(&A)";
            this.menuItemLogAllDelete.Click += new System.EventHandler(this.menuItemLogAllDelete_Click);
            // 
            // menuItemBrandList
            // 
            this.menuItemBrandList.Index = 1;
            this.menuItemBrandList.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemBrandListEdit});
            this.menuItemBrandList.Text = "銘柄リスト(&L)";
            // 
            // menuItemBrandListEdit
            // 
            this.menuItemBrandListEdit.Index = 0;
            this.menuItemBrandListEdit.Text = "編集(&E)";
            this.menuItemBrandListEdit.Click += new System.EventHandler(this.menuItemBrandListEdit_Click);
            // 
            // menuItemHelp
            // 
            this.menuItemHelp.Index = 2;
            this.menuItemHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemMan,
            this.menuItemVersion});
            this.menuItemHelp.Text = "ヘルプ(&H)";
            // 
            // menuItemMan
            // 
            this.menuItemMan.Index = 0;
            this.menuItemMan.Shortcut = System.Windows.Forms.Shortcut.F1;
            this.menuItemMan.Text = "マニュアル(&M)";
            this.menuItemMan.Click += new System.EventHandler(this.menuItemMan_Click);
            // 
            // menuItemVersion
            // 
            this.menuItemVersion.Index = 1;
            this.menuItemVersion.Text = "バージョン情報(&V)";
            this.menuItemVersion.Click += new System.EventHandler(this.menuItemVersion_Click);
            // 
            // panelLeft
            // 
            this.panelLeft.Controls.Add(this.ptFileTreeView);
            this.panelLeft.Controls.Add(this.panelSelect);
            this.panelLeft.Dock = System.Windows.Forms.DockStyle.Left;
            this.panelLeft.Location = new System.Drawing.Point(0, 0);
            this.panelLeft.Name = "panelLeft";
            this.panelLeft.Size = new System.Drawing.Size(184, 400);
            this.panelLeft.TabIndex = 0;
            // 
            // ptFileTreeView
            // 
            this.ptFileTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
            this.ptFileTreeView.HideSelection = false;
            this.ptFileTreeView.ImageIndex = 0;
            this.ptFileTreeView.Location = new System.Drawing.Point(0, 0);
            this.ptFileTreeView.Name = "ptFileTreeView";
            this.ptFileTreeView.RootDirectory = null;
            this.ptFileTreeView.SelectedImageIndex = 0;
            this.ptFileTreeView.Size = new System.Drawing.Size(184, 308);
            this.ptFileTreeView.TabIndex = 0;
            this.ptFileTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.ptFileTreeView_AfterSelect);
            // 
            // panelSelect
            // 
            this.panelSelect.Controls.Add(this.labelMode);
            this.panelSelect.Controls.Add(this.labelBrandList);
            this.panelSelect.Controls.Add(this.comboBoxBrandList);
            this.panelSelect.Controls.Add(this.radioButtonDaily);
            this.panelSelect.Controls.Add(this.radioButtonWeekly);
            this.panelSelect.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.panelSelect.Location = new System.Drawing.Point(0, 308);
            this.panelSelect.Name = "panelSelect";
            this.panelSelect.Size = new System.Drawing.Size(184, 92);
            this.panelSelect.TabIndex = 1;
            // 
            // labelMode
            // 
            this.labelMode.Location = new System.Drawing.Point(12, 24);
            this.labelMode.Name = "labelMode";
            this.labelMode.Size = new System.Drawing.Size(60, 16);
            this.labelMode.TabIndex = 3;
            this.labelMode.Text = "期間モード";
            // 
            // labelBrandList
            // 
            this.labelBrandList.Location = new System.Drawing.Point(12, 56);
            this.labelBrandList.Name = "labelBrandList";
            this.labelBrandList.Size = new System.Drawing.Size(60, 16);
            this.labelBrandList.TabIndex = 2;
            this.labelBrandList.Text = "銘柄リスト";
            // 
            // comboBoxBrandList
            // 
            this.comboBoxBrandList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxBrandList.Location = new System.Drawing.Point(72, 52);
            this.comboBoxBrandList.Name = "comboBoxBrandList";
            this.comboBoxBrandList.Size = new System.Drawing.Size(104, 20);
            this.comboBoxBrandList.Sorted = true;
            this.comboBoxBrandList.TabIndex = 1;
            this.comboBoxBrandList.SelectedIndexChanged += new System.EventHandler(this.comboBoxBrandList_SelectedIndexChanged);
            // 
            // radioButtonDaily
            // 
            this.radioButtonDaily.Checked = true;
            this.radioButtonDaily.Location = new System.Drawing.Point(72, 20);
            this.radioButtonDaily.Name = "radioButtonDaily";
            this.radioButtonDaily.Size = new System.Drawing.Size(52, 20);
            this.radioButtonDaily.TabIndex = 0;
            this.radioButtonDaily.TabStop = true;
            this.radioButtonDaily.Text = "日足";
            // 
            // radioButtonWeekly
            // 
            this.radioButtonWeekly.Location = new System.Drawing.Point(124, 20);
            this.radioButtonWeekly.Name = "radioButtonWeekly";
            this.radioButtonWeekly.Size = new System.Drawing.Size(52, 20);
            this.radioButtonWeekly.TabIndex = 1;
            this.radioButtonWeekly.Text = "週足";
            // 
            // splitterLeft
            // 
            this.splitterLeft.Enabled = false;
            this.splitterLeft.Location = new System.Drawing.Point(184, 0);
            this.splitterLeft.Name = "splitterLeft";
            this.splitterLeft.Size = new System.Drawing.Size(3, 400);
            this.splitterLeft.TabIndex = 0;
            this.splitterLeft.TabStop = false;
            // 
            // tabControl
            // 
            this.tabControl.Appearance = System.Windows.Forms.TabAppearance.FlatButtons;
            this.tabControl.Controls.Add(this.tabPageExecute);
            this.tabControl.Controls.Add(this.tabPagePerformance);
            this.tabControl.Controls.Add(this.tabPageHistory);
            this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl.ImageList = this.imageListTab;
            this.tabControl.Location = new System.Drawing.Point(187, 0);
            this.tabControl.Name = "tabControl";
            this.tabControl.SelectedIndex = 0;
            this.tabControl.Size = new System.Drawing.Size(363, 400);
            this.tabControl.TabIndex = 1;
            // 
            // tabPageExecute
            // 
            this.tabPageExecute.AutoScroll = true;
            this.tabPageExecute.Controls.Add(this.progressBarExecute);
            this.tabPageExecute.Controls.Add(this.buttonExecute);
            this.tabPageExecute.Controls.Add(this.simulateTextBox);
            this.tabPageExecute.ImageIndex = 0;
            this.tabPageExecute.Location = new System.Drawing.Point(4, 26);
            this.tabPageExecute.Name = "tabPageExecute";
            this.tabPageExecute.Size = new System.Drawing.Size(355, 370);
            this.tabPageExecute.TabIndex = 0;
            this.tabPageExecute.Text = "実行";
            // 
            // progressBarExecute
            // 
            this.progressBarExecute.Location = new System.Drawing.Point(92, 340);
            this.progressBarExecute.Name = "progressBarExecute";
            this.progressBarExecute.Size = new System.Drawing.Size(248, 16);
            this.progressBarExecute.TabIndex = 2;
            // 
            // buttonExecute
            // 
            this.buttonExecute.Location = new System.Drawing.Point(8, 336);
            this.buttonExecute.Name = "buttonExecute";
            this.buttonExecute.Size = new System.Drawing.Size(75, 23);
            this.buttonExecute.TabIndex = 1;
            this.buttonExecute.Text = "実行";
            this.buttonExecute.Click += new System.EventHandler(this.buttonExecute_Click);
            // 
            // simulateTextBox
            // 
            this.simulateTextBox.BackColor = System.Drawing.SystemColors.Window;
            this.simulateTextBox.Dock = System.Windows.Forms.DockStyle.Top;
            this.simulateTextBox.ForeColor = System.Drawing.SystemColors.WindowText;
            this.simulateTextBox.Location = new System.Drawing.Point(0, 0);
            this.simulateTextBox.MaxLength = 0;
            this.simulateTextBox.Multiline = true;
            this.simulateTextBox.Name = "simulateTextBox";
            this.simulateTextBox.ReadOnly = true;
            this.simulateTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.simulateTextBox.Size = new System.Drawing.Size(355, 320);
            this.simulateTextBox.System = null;
            this.simulateTextBox.TabIndex = 0;
            // 
            // tabPagePerformance
            // 
            this.tabPagePerformance.AutoScroll = true;
            this.tabPagePerformance.Controls.Add(this.progressBarPerformance);
            this.tabPagePerformance.Controls.Add(this.buttonPerformance);
            this.tabPagePerformance.Controls.Add(this.tabControlPerformance);
            this.tabPagePerformance.ImageIndex = 1;
            this.tabPagePerformance.Location = new System.Drawing.Point(4, 26);
            this.tabPagePerformance.Name = "tabPagePerformance";
            this.tabPagePerformance.Size = new System.Drawing.Size(355, 370);
            this.tabPagePerformance.TabIndex = 1;
            this.tabPagePerformance.Text = "成績計算";
            // 
            // progressBarPerformance
            // 
            this.progressBarPerformance.Location = new System.Drawing.Point(92, 340);
            this.progressBarPerformance.Name = "progressBarPerformance";
            this.progressBarPerformance.Size = new System.Drawing.Size(248, 16);
            this.progressBarPerformance.TabIndex = 2;
            // 
            // buttonPerformance
            // 
            this.buttonPerformance.Location = new System.Drawing.Point(8, 336);
            this.buttonPerformance.Name = "buttonPerformance";
            this.buttonPerformance.Size = new System.Drawing.Size(75, 23);
            this.buttonPerformance.TabIndex = 1;
            this.buttonPerformance.Text = "計算";
            this.buttonPerformance.Click += new System.EventHandler(this.buttonPerformance_Click);
            // 
            // tabControlPerformance
            // 
            this.tabControlPerformance.Controls.Add(this.tabPagePerformanceSummery);
            this.tabControlPerformance.Controls.Add(this.tabPagePerformanceProfitGraph);
            this.tabControlPerformance.Dock = System.Windows.Forms.DockStyle.Top;
            this.tabControlPerformance.Location = new System.Drawing.Point(0, 0);
            this.tabControlPerformance.Name = "tabControlPerformance";
            this.tabControlPerformance.SelectedIndex = 0;
            this.tabControlPerformance.Size = new System.Drawing.Size(355, 320);
            this.tabControlPerformance.TabIndex = 0;
            // 
            // tabPagePerformanceSummery
            // 
            this.tabPagePerformanceSummery.Controls.Add(this.richTextBoxPerformanceSummery);
            this.tabPagePerformanceSummery.Location = new System.Drawing.Point(4, 21);
            this.tabPagePerformanceSummery.Name = "tabPagePerformanceSummery";
            this.tabPagePerformanceSummery.Size = new System.Drawing.Size(347, 295);
            this.tabPagePerformanceSummery.TabIndex = 0;
            this.tabPagePerformanceSummery.Text = "サマリー";
            // 
            // richTextBoxPerformanceSummery
            // 
            this.richTextBoxPerformanceSummery.BackColor = System.Drawing.SystemColors.Window;
            this.richTextBoxPerformanceSummery.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBoxPerformanceSummery.Location = new System.Drawing.Point(0, 0);
            this.richTextBoxPerformanceSummery.Name = "richTextBoxPerformanceSummery";
            this.richTextBoxPerformanceSummery.ReadOnly = true;
            this.richTextBoxPerformanceSummery.Size = new System.Drawing.Size(347, 295);
            this.richTextBoxPerformanceSummery.TabIndex = 0;
            this.richTextBoxPerformanceSummery.Text = "";
            // 
            // tabPagePerformanceProfitGraph
            // 
            this.tabPagePerformanceProfitGraph.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.tabPagePerformanceProfitGraph.Controls.Add(this.profitGraphBox);
            this.tabPagePerformanceProfitGraph.Location = new System.Drawing.Point(4, 21);
            this.tabPagePerformanceProfitGraph.Name = "tabPagePerformanceProfitGraph";
            this.tabPagePerformanceProfitGraph.Size = new System.Drawing.Size(347, 295);
            this.tabPagePerformanceProfitGraph.TabIndex = 1;
            this.tabPagePerformanceProfitGraph.Text = "利益曲線";
            // 
            // profitGraphBox
            // 
            this.profitGraphBox.BackColor = System.Drawing.SystemColors.Window;
            this.profitGraphBox.Dock = System.Windows.Forms.DockStyle.Fill;
            this.profitGraphBox.Location = new System.Drawing.Point(0, 0);
            this.profitGraphBox.Name = "profitGraphBox";
            this.profitGraphBox.ProfitList = null;
            this.profitGraphBox.Size = new System.Drawing.Size(343, 291);
            this.profitGraphBox.TabIndex = 0;
            // 
            // tabPageHistory
            // 
            this.tabPageHistory.AutoScroll = true;
            this.tabPageHistory.Controls.Add(this.buttonHistory);
            this.tabPageHistory.Controls.Add(this.labelDateRange);
            this.tabPageHistory.Controls.Add(this.dateTimePickerHistoryDateMax);
            this.tabPageHistory.Controls.Add(this.dateTimePickerHistoryDateMin);
            this.tabPageHistory.Controls.Add(this.listViewHistory);
            this.tabPageHistory.ImageIndex = 2;
            this.tabPageHistory.Location = new System.Drawing.Point(4, 26);
            this.tabPageHistory.Name = "tabPageHistory";
            this.tabPageHistory.Size = new System.Drawing.Size(355, 370);
            this.tabPageHistory.TabIndex = 2;
            this.tabPageHistory.Text = "履歴検索";
            // 
            // buttonHistory
            // 
            this.buttonHistory.Location = new System.Drawing.Point(260, 336);
            this.buttonHistory.Name = "buttonHistory";
            this.buttonHistory.Size = new System.Drawing.Size(75, 23);
            this.buttonHistory.TabIndex = 4;
            this.buttonHistory.Text = "検索";
            this.buttonHistory.Click += new System.EventHandler(this.buttonHistory_Click);
            // 
            // labelDateRange
            // 
            this.labelDateRange.Location = new System.Drawing.Point(120, 340);
            this.labelDateRange.Name = "labelDateRange";
            this.labelDateRange.Size = new System.Drawing.Size(20, 16);
            this.labelDateRange.TabIndex = 2;
            this.labelDateRange.Text = "〜";
            // 
            // dateTimePickerHistoryDateMax
            // 
            this.dateTimePickerHistoryDateMax.Location = new System.Drawing.Point(140, 336);
            this.dateTimePickerHistoryDateMax.Name = "dateTimePickerHistoryDateMax";
            this.dateTimePickerHistoryDateMax.Size = new System.Drawing.Size(108, 19);
            this.dateTimePickerHistoryDateMax.TabIndex = 3;
            // 
            // dateTimePickerHistoryDateMin
            // 
            this.dateTimePickerHistoryDateMin.Location = new System.Drawing.Point(12, 336);
            this.dateTimePickerHistoryDateMin.Name = "dateTimePickerHistoryDateMin";
            this.dateTimePickerHistoryDateMin.Size = new System.Drawing.Size(108, 19);
            this.dateTimePickerHistoryDateMin.TabIndex = 1;
            // 
            // listViewHistory
            // 
            this.listViewHistory.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeaderHistoryDate,
            this.columnHeaderHistoryCode,
            this.columnHeaderHistoryName,
            this.columnHeaderHistoryPrice,
            this.columnHeaderHistoryNumber,
            this.columnHeaderHistoryOrder});
            this.listViewHistory.ContextMenu = this.historyContextMenu;
            this.listViewHistory.Dock = System.Windows.Forms.DockStyle.Top;
            this.listViewHistory.FullRowSelect = true;
            this.listViewHistory.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
            this.listViewHistory.Location = new System.Drawing.Point(0, 0);
            this.listViewHistory.Name = "listViewHistory";
            this.listViewHistory.OwnerDraw = true;
            this.listViewHistory.Size = new System.Drawing.Size(355, 320);
            this.listViewHistory.TabIndex = 0;
            this.listViewHistory.UseCompatibleStateImageBehavior = false;
            this.listViewHistory.View = System.Windows.Forms.View.Details;
            // 
            // columnHeaderHistoryDate
            // 
            this.columnHeaderHistoryDate.Text = "日付";
            // 
            // columnHeaderHistoryCode
            // 
            this.columnHeaderHistoryCode.Text = "コード";
            this.columnHeaderHistoryCode.Width = 40;
            // 
            // columnHeaderHistoryName
            // 
            this.columnHeaderHistoryName.Text = "銘柄名";
            this.columnHeaderHistoryName.Width = 70;
            // 
            // columnHeaderHistoryPrice
            // 
            this.columnHeaderHistoryPrice.Text = "値段(円)";
            // 
            // columnHeaderHistoryNumber
            // 
            this.columnHeaderHistoryNumber.Text = "株数";
            this.columnHeaderHistoryNumber.Width = 50;
            // 
            // columnHeaderHistoryOrder
            // 
            this.columnHeaderHistoryOrder.Text = "注文";
            this.columnHeaderHistoryOrder.Width = 40;
            // 
            // historyContextMenu
            // 
            this.historyContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.copyHistory});
            // 
            // copyHistory
            // 
            this.copyHistory.Index = 0;
            this.copyHistory.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
            this.copyHistory.ShowShortcut = false;
            this.copyHistory.Text = "コピー(&C)";
            this.copyHistory.Click += new System.EventHandler(this.copyHistory_Click);
            // 
            // imageListTab
            // 
            this.imageListTab.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListTab.ImageStream")));
            this.imageListTab.TransparentColor = System.Drawing.Color.Transparent;
            this.imageListTab.Images.SetKeyName(0, "");
            this.imageListTab.Images.SetKeyName(1, "");
            this.imageListTab.Images.SetKeyName(2, "");
            // 
            // backgroundWorkerPerformance
            // 
            this.backgroundWorkerPerformance.WorkerReportsProgress = true;
            this.backgroundWorkerPerformance.WorkerSupportsCancellation = true;
            this.backgroundWorkerPerformance.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerPerformance_DoWork);
            this.backgroundWorkerPerformance.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerPerformance_RunWorkerCompleted);
            this.backgroundWorkerPerformance.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerPerformance_ProgressChanged);
            // 
            // backgroundWorkerExecute
            // 
            this.backgroundWorkerExecute.WorkerReportsProgress = true;
            this.backgroundWorkerExecute.WorkerSupportsCancellation = true;
            this.backgroundWorkerExecute.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerExecute_DoWork);
            this.backgroundWorkerExecute.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerExecute_RunWorkerCompleted);
            this.backgroundWorkerExecute.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerExecute_ProgressChanged);
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.ClientSize = new System.Drawing.Size(550, 400);
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.splitterLeft);
            this.Controls.Add(this.panelLeft);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.KeyPreview = true;
            this.MaximizeBox = false;
            this.Menu = this.mainMenu;
            this.Name = "MainForm";
            this.Text = "PtSim";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyDown);
            this.panelLeft.ResumeLayout(false);
            this.panelSelect.ResumeLayout(false);
            this.tabControl.ResumeLayout(false);
            this.tabPageExecute.ResumeLayout(false);
            this.tabPageExecute.PerformLayout();
            this.tabPagePerformance.ResumeLayout(false);
            this.tabControlPerformance.ResumeLayout(false);
            this.tabPagePerformanceSummery.ResumeLayout(false);
            this.tabPagePerformanceProfitGraph.ResumeLayout(false);
            this.tabPageHistory.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// 環境設定ファイルを読み込みます。
        /// </summary>
        private void EnvRead()
        {
            try
            {
                configFile.Read();
            }
            catch
            {
                return;
            }
            try
            {
                // フォーム
                if (int.Parse(configFile["Mode"]) == 1)
                    this.radioButtonWeekly.Checked = true;
                BrandList brandList = BrandListTable.GetRecord(int.Parse(configFile["BrandListId"]));
                if (brandList != null)
                {
                    BrandListItem item = new BrandListItem(brandList);
                    this.comboBoxBrandList.SelectedItem = item;
                }
            }
            catch (ArgumentNullException) { }
            catch (FormatException) { }
        }

        /// <summary>
        /// 環境設定ファイルを書き込みます。
        /// </summary>
        private void EnvWrite()
        {
            // フォーム
            int mode = this.radioButtonDaily.Checked ? 0 : 1;
            configFile["Mode"] = mode.ToString();

            object item = this.comboBoxBrandList.SelectedItem;
            if (item != null)
            {
                BrandList brandList = ((BrandListItem)item).BrandList;
                configFile["BrandListId"] = brandList.Id.ToString();
            }

            configFile.Write();
        }

        /// <summary>
        /// XML形式の設定ファイルを書き込む。
        /// </summary>
        private void ConfigWrite()
        {
            string protra = "";
            string dataSource = "";
            string favorite = "";
            try
            {
                XmlReader reader = XmlReader.Create(Global.DirConf + Path.DirectorySeparatorChar + "config.xml");
                try
                {
                    if (reader.ReadToFollowing("protra"))
                        protra = reader.ReadOuterXml();
                    if (reader.ReadToFollowing("data-source"))
                        dataSource = reader.ReadOuterXml();
                    if (reader.ReadToFollowing("list")) // 最初はお気に入り。
                        favorite = reader.ReadOuterXml();
                }
                catch (XmlException)
                { } // config.xmlが壊れたときに起こりうる。
                reader.Close();
            }
            catch (FileNotFoundException)
            { }
            XmlWriter writer = XmlWriter.Create(Global.DirConf + Path.DirectorySeparatorChar + "config.xml");
            writer.WriteStartElement("config");
            writer.WriteWhitespace("\n");
            writer.WriteRaw(protra);
            writer.WriteWhitespace("\n");
            writer.WriteRaw(dataSource);
            writer.WriteWhitespace("\n");
            writer.WriteStartElement("ptsim");
            writer.WriteAttributeString("mode", (radioButtonDaily.Checked) ? "0" : "1");
            BrandListItem item = (BrandListItem)comboBoxBrandList.SelectedItem;
            writer.WriteAttributeString("list", (item != null) ? item.BrandList.Name : "");
            writer.WriteEndElement();
            writer.WriteWhitespace("\n");
            writer.WriteStartElement("brand-lists");
            writer.WriteWhitespace("\n");
            writer.WriteRaw(favorite);
            writer.WriteWhitespace("\n");
            foreach (BrandList brandList in BrandListTable.GetAllRecords())
            {
                writer.WriteStartElement("list");
                writer.WriteAttributeString("name", brandList.Name);
                writer.WriteWhitespace("\n");
                foreach (Brand brand in BrandList_BrandTable.GetBrands(brandList.Id))
                {
                    writer.WriteValue(brand.Code);
                    writer.WriteWhitespace(" ");
                }
                writer.WriteWhitespace("\n");
                writer.WriteEndElement();
                writer.WriteWhitespace("\n");
            }
            writer.WriteEndElement();
            writer.WriteWhitespace("\n");
            writer.WriteEndElement();
            writer.Close();
        }

        /// <summary>
        /// シミュレーションを実行します。
        /// </summary>
        private void Execute(BackgroundWorker worker, DoWorkEventArgs e)
        {
            TradingSystem system = (TradingSystem)((object[])e.Argument)[0];
            Brand[] brands = (Brand[])((object[])e.Argument)[1];

            simulateTextBox.System = system; // 構文解析が行われる。
            bool isDaily = this.radioButtonDaily.Checked;
            for (int i = 0; i < brands.Length; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                Brand brand = brands[i];
                Price[] prices;
                if (isDaily)
                    prices = PriceTable.PriceList(brand.Id);
                else
                    prices = PriceTable.WeeklyPriceList(brand.Id);
                this.simulateTextBox.Simulate(prices, worker, e);
                worker.ReportProgress(100 * (i + 1) / brands.Length);
            }
        }

        /// <summary>
        /// 成績を計算します。
        /// </summary>
        private string Performance(BackgroundWorker worker, DoWorkEventArgs e)
        {
            TradingSystem system = (TradingSystem)((object[])e.Argument)[0];
            Brand[] brands = (Brand[])((object[])e.Argument)[1];
            string targetName = (string)((object[])e.Argument)[2];

            ProfitList profitList = new ProfitList();
            int allTradeNum = 0;			// 全トレード数
            int winTradeNum = 0;			// 勝ちトレード数
            int loseTradeNum = 0;			// 負けトレード数
            float allTradeAveRatio = 0;		// 全トレード平均利率
            float winTradeAveRatio = 0;		// 勝ちトレード平均利率
            float loseTradeAveRatio = 0;	// 負けトレード平均損率
            float winTradeMaxRatio = 0;		// 勝ちトレード最大利率
            float loseTradeMinRatio = 0;	// 負けトレード最大損率
            float allTradeAveSpan = 0;		// 全トレード平均期間
            float winTradeAveSpan = 0;		// 勝ちトレード平均期間
            float loseTradeAveSpan = 0;		// 負けトレード平均期間
            float allTradeProfit = 0;		// 純利益
            float winTradeProfit = 0;		// 勝ちトレード総利益
            float loseTradeProfit = 0;		// 負けトレード総損失
            float allTradeAveProfit = 0;	// 全トレード平均利益
            float winTradeAveProfit = 0;	// 勝ちトレード平均利益
            float loseTradeAveProfit = 0;	// 負けトレード平均損失
            float winTradeMaxProfit = 0;	// 勝ちトレード最大利益
            float loseTradeMinProfit = 0;	// 負けトレード最大損失
            float pf = 0;					// プロフィットファクター
            float ddBook = 0;				// ドローダウン(簿価)
            float ddMarket = 0;				// ドローダウン(時価)
            int currentTradeNum = 0;		// 現在進行中のトレード数

            bool isDaily = this.radioButtonDaily.Checked;
            for (int i = 0; i < brands.Length; i++)
            {
                Brand brand = brands[i];
                Price[] prices;
                if (isDaily)
                    prices = PriceTable.PriceList(brand.Id);
                else
                    prices = PriceTable.WeeklyPriceList(brand.Id);
                SystemLog[] logs = SystemLogTable.GetRecords(system.Id, brand.Id);

                int index = 0;
                DateTime beginDate = new DateTime(); // トレード開始日
                bool isHolding = false; // 保有しているか？
                int holdingNum = 0;     // 保有株数
                float buySum = 0;       // 買いの総和
                float sellSum = 0;      // 売りの総和
                int prePrice = 0;       // 前日の価格
                for (int j = 0; j < prices.Length; j++)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return null;
                    }
                    Profit profit = profitList[prices[j].Date];
                    int price = prices[j].Close;
                    if (isHolding && price > 0 && prePrice > 0)
                    {
                        profit.MarketProfit += holdingNum * (price - prePrice);
                        prePrice = price;
                    }
                    else if (price > 0)
                    {
                        prePrice = price;
                    }

                    if (index < logs.Length && logs[index].Date == prices[j].Date)
                    {
                        SystemLog log = logs[index++];
                        if (log.Order == 0) // 買い
                        {
                            holdingNum += log.Number;
                            buySum += log.Number * log.Price;
                            profit.MarketProfit += log.Number * (prePrice - log.Price);
                        }
                        else // 売り
                        {
                            holdingNum -= log.Number;
                            sellSum += log.Number * log.Price;
                            profit.MarketProfit -= log.Number * (prePrice - log.Price);
                        }

                        if (!isHolding) // トレードの開始
                        {
                            beginDate = log.Date;
                            isHolding = true;
                        }
                        else if (holdingNum == 0) // トレードの終了
                        {
                            allTradeNum++;
                            float ratio = sellSum / buySum - 1;
                            allTradeAveRatio += ratio;
                            int span = (log.Date - beginDate).Days;
                            allTradeAveSpan += span;
                            float p = sellSum - buySum;
                            profit.BookProfit += p;
                            allTradeProfit += p;
                            if (buySum < sellSum) // 勝ち
                            {
                                winTradeNum++;
                                winTradeAveRatio += ratio;
                                if (ratio > winTradeMaxRatio)
                                    winTradeMaxRatio = ratio;
                                winTradeAveSpan += span;
                                winTradeProfit += p;
                                if (p > winTradeMaxProfit)
                                    winTradeMaxProfit = p;
                            }
                            else // 負け
                            {
                                if (ratio < loseTradeMinRatio)
                                    loseTradeMinRatio = ratio;
                                if (p < loseTradeMinProfit)
                                    loseTradeMinProfit = p;
                            }

                            isHolding = false;
                            buySum = sellSum = 0;
                        }
                    }
                }

                if (isHolding)
                    currentTradeNum++;

                worker.ReportProgress(100 * (i + 1) / brands.Length);
            }

            loseTradeNum = allTradeNum - winTradeNum;
            float winProb = allTradeNum == 0 ? 0 : (float)100 * winTradeNum / allTradeNum;
            float loseProb = allTradeNum == 0 ? 0 : 100 - winProb;
            loseTradeAveRatio = 100 * (allTradeAveRatio - winTradeAveRatio) / loseTradeNum;
            allTradeAveRatio = 100 * allTradeAveRatio / allTradeNum;
            winTradeAveRatio = 100 * winTradeAveRatio / winTradeNum;
            loseTradeAveSpan = (allTradeAveSpan - winTradeAveSpan) / loseTradeNum;
            winTradeMaxRatio = 100 * winTradeMaxRatio;
            loseTradeMinRatio = 100 * loseTradeMinRatio;
            allTradeAveSpan = allTradeAveSpan / allTradeNum;
            winTradeAveSpan = winTradeAveSpan / winTradeNum;
            loseTradeProfit = allTradeProfit - winTradeProfit;
            allTradeAveProfit = allTradeProfit / allTradeNum;
            winTradeAveProfit = winTradeProfit / winTradeNum;
            loseTradeAveProfit = loseTradeProfit / loseTradeNum;
            pf = -winTradeProfit / loseTradeProfit;
            // 累積利益に変換
            profitList.Accumulate();
            Profit dd = profitList.MaxDrawDown();
            ddBook = dd.BookProfit;
            ddMarket = dd.MarketProfit;
            profitGraphBox.ProfitList = profitList;

            string msg = "ファイル: " + system.File + "\r\n" +
                "期間モード: " + (isDaily ? "日足" : "週足") + "\r\n" +
                "対象銘柄: " + targetName + "\r\n" +
                profitList.MinDate.ToShortDateString() + "〜" + profitList.MaxDate.ToShortDateString() + "における成績です。\r\n" +
                "----------------------------------------\r\n" +
                "全トレード数\t\t" + allTradeNum + "\r\n" +
                "勝ちトレード数(勝率)\t" + winTradeNum + "(" + winProb.ToString("N") + "%)\r\n" +
                "負けトレード数(負率)\t" + loseTradeNum + "(" + loseProb.ToString("N") + "%)\r\n\r\n" +
                "全トレード平均利率\t" + allTradeAveRatio.ToString("N") + "%\r\n" +
                "勝ちトレード平均利率\t" + winTradeAveRatio.ToString("N") + "%\r\n" +
                "負けトレード平均損率\t" + loseTradeAveRatio.ToString("N") + "%\r\n\r\n" +
                "勝ちトレード最大利率\t" + winTradeMaxRatio.ToString("N") + "%\r\n" +
                "負けトレード最大損率\t" + loseTradeMinRatio.ToString("N") + "%\r\n\r\n" +
                "全トレード平均期間\t" + allTradeAveSpan.ToString("N") + "日\r\n" +
                "勝ちトレード平均期間\t" + winTradeAveSpan.ToString("N") + "日\r\n" +
                "負けトレード平均期間\t" + loseTradeAveSpan.ToString("N") + "日\r\n" +
                "----------------------------------------\r\n" +
                "純利益\t\t\t" + allTradeProfit.ToString("C") + "\r\n" +
                "勝ちトレード総利益\t\t" + winTradeProfit.ToString("C") + "\r\n" +
                "負けトレード総損失\t\t" + loseTradeProfit.ToString("C") + "\r\n\r\n" +
                "全トレード平均利益\t" + allTradeAveProfit.ToString("C") + "\r\n" +
                "勝ちトレード平均利益\t" + winTradeAveProfit.ToString("C") + "\r\n" +
                "負けトレード平均損失\t" + loseTradeAveProfit.ToString("C") + "\r\n\r\n" +
                "勝ちトレード最大利益\t" + winTradeMaxProfit.ToString("C") + "\r\n" +
                "負けトレード最大損失\t" + loseTradeMinProfit.ToString("C") + "\r\n\r\n" +
                "プロフィットファクター\t\t" + pf.ToString("N") + "\r\n\r\n" +
                "最大ドローダウン(簿価)\t" + ddBook.ToString("C") + "\r\n" +
                "最大ドローダウン(時価)\t" + ddMarket.ToString("C") + "\r\n" +
                "----------------------------------------\r\n" +
                "現在進行中のトレード数\t" + currentTradeNum + "\r\n";
            return msg;
        }

        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process cps = Process.GetCurrentProcess();
            Process[] ps = Process.GetProcessesByName(cps.ProcessName);
            if (ps.Length > 1)
            {
                int i = 0;
                if (ps[0].Id == cps.Id)
                    i = 1;
                SetForegroundWindow(ps[i].MainWindowHandle.ToInt32());
                return;
            }

            Application.Run(new MainForm());
        }

        private void MainForm_Load(object sender, System.EventArgs e)
        {
            BrandList[] brandLists = BrandListTable.GetAllRecords();
            foreach (BrandList brandList in brandLists)
                this.comboBoxBrandList.Items.Add(new BrandListItem(brandList));
            if (this.comboBoxBrandList.Items.Count > 0)
                this.comboBoxBrandList.SelectedIndex = 0;

            this.dateTimePickerHistoryDateMin.Value = DateTime.Now.AddMonths(-1);
            this.ptFileTreeView.RootDirectory = Global.DirSystem;

            EnvRead();
        }

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

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5 || (e.KeyCode == Keys.R && e.Control))
                ptFileTreeView.RootDirectory = Global.DirSystem;
        }

        private void menuItemLogDelete_Click(object sender, System.EventArgs e)
        {
            TradingSystem system = this.GetSelectedSystem();
            if (system == null)
                return;
            string msg = string.Format(
                "ファイル: {0}\n期間モード: {1}\nのシステムログを削除します。よろしいですか？",
                system.File, system.Mode == 0 ? "日足" : "週足");
            DialogResult result = MessageBox.Show(
                this, msg, "確認", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            if (result == DialogResult.OK)
                SimulateTextBox.DeleteLog(system.Id);
        }

        private void menuItemLogAllDelete_Click(object sender, System.EventArgs e)
        {
            DialogResult result = MessageBox.Show(this,
                "システムログをすべて削除します。よろしいですか？",
                "確認", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.OK)
                SimulateTextBox.DeleteLog();
        }

        private void menuItemBrandListEdit_Click(object sender, System.EventArgs e)
        {
            Form dialog = new EditBrandListDialog();
            dialog.ShowDialog(this);

            object item = this.comboBoxBrandList.SelectedItem;
            this.comboBoxBrandList.Items.Clear();
            BrandList[] brandLists = BrandListTable.GetAllRecords();
            foreach (BrandList brandList in brandLists)
                this.comboBoxBrandList.Items.Add(new BrandListItem(brandList));
            if (item != null && this.comboBoxBrandList.Items.Contains(item))
                this.comboBoxBrandList.SelectedItem = item;
            else if (this.comboBoxBrandList.Items.Count > 0)
                this.comboBoxBrandList.SelectedIndex = 0;
        }

        private void menuItemMan_Click(object sender, System.EventArgs e)
        {
            Process.Start(Global.PathMan);
        }

        private void menuItemVersion_Click(object sender, System.EventArgs e)
        {
            Form dialog = new VersionDialog();
            dialog.ShowDialog(this);
        }

        private void ptFileTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            this.comboBoxBrandList_SelectedIndexChanged(sender, e);
        }

        private void comboBoxBrandList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (this.ptFileTreeView.SelectedRelativeFile != null
                && this.comboBoxBrandList.SelectedItem != null)
            {
                if (!backgroundWorkerExecute.IsBusy && !backgroundWorkerPerformance.IsBusy)
                {
                    this.buttonExecute.Enabled = true;
                    this.buttonPerformance.Enabled = true;
                    this.menuItemLogDelete.Enabled = true;
                }
                this.buttonHistory.Enabled = true;
            }
            else
            {
                if (!backgroundWorkerExecute.IsBusy && !backgroundWorkerPerformance.IsBusy)
                {
                    this.buttonExecute.Enabled = false;
                    this.buttonPerformance.Enabled = false;
                    this.menuItemLogDelete.Enabled = false;
                }
                this.buttonHistory.Enabled = false;
            }
        }

        private void buttonExecute_Click(object sender, System.EventArgs e)
        {
            if (backgroundWorkerExecute.IsBusy)
            {
                backgroundWorkerExecute.CancelAsync();
                return;
            }

            TradingSystem system = this.GetSelectedSystem();
            if (system == null)
                return;
            Brand[] brands = this.GetSelectedBrands();
            if (brands == null)
                return;

            // 各種操作を無効化
            this.buttonExecute.Text = "中断";
            this.buttonPerformance.Enabled = false;
            this.menuItemLogDelete.Enabled = false;
            this.menuItemLogAllDelete.Enabled = false;
            this.menuItemBrandListEdit.Enabled = false;
            // simulateTextBoxを初期化
            this.simulateTextBox.Clear();

            backgroundWorkerExecute.RunWorkerAsync(new object[] { system, brands });
        }

        private void backgroundWorkerExecute_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            Execute(worker, e);
        }

        private void backgroundWorkerExecute_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBarExecute.Value = e.ProgressPercentage;
        }

        private void backgroundWorkerExecute_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                this.simulateTextBox.AppendText(e.Error.Message + "\r\nエラーが発生したので実行を中断します。");
            else if (e.Cancelled)
                this.simulateTextBox.AppendText("中断されました。");
            else
                this.simulateTextBox.AppendText("正常に終了しました。\r\n");

            // 各種操作を復旧する。
            this.buttonExecute.Text = "実行";
            this.progressBarExecute.Value = 0;
            this.menuItemLogAllDelete.Enabled = true;
            if (this.ptFileTreeView.SelectedRelativeFile != null
                && this.comboBoxBrandList.SelectedItem != null)
            {
                this.buttonPerformance.Enabled = true;
                this.menuItemLogDelete.Enabled = true;
                this.menuItemBrandListEdit.Enabled = true;
            }
            else
            {
                this.buttonExecute.Enabled = false;
            }
            this.progressBarPerformance.Value = 0;
        }

        private void buttonPerformance_Click(object sender, System.EventArgs e)
        {
            if (backgroundWorkerPerformance.IsBusy)
            {
                backgroundWorkerPerformance.CancelAsync();
                return;
            }
            TradingSystem system = this.GetSelectedSystem();
            if (system == null)
                return;
            Brand[] brands = this.GetSelectedBrands();
            if (brands == null)
                return;
            string targetName = this.comboBoxBrandList.Text;

            // 各種操作を無効にする。
            this.buttonPerformance.Text = "中断";
            this.buttonExecute.Enabled = false;
            this.menuItemLogDelete.Enabled = false;
            this.menuItemLogAllDelete.Enabled = false;
            this.menuItemBrandListEdit.Enabled = false;
            this.richTextBoxPerformanceSummery.Clear();

            // profitGraphBoxを初期化する。
            this.profitGraphBox.ProfitList = null;

            backgroundWorkerPerformance.RunWorkerAsync(new object[] { system, brands, targetName });
        }

        private void backgroundWorkerPerformance_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            e.Result = Performance(worker, e);
        }

        private void backgroundWorkerPerformance_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBarPerformance.Value = e.ProgressPercentage;
        }

        private void backgroundWorkerPerformance_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                this.richTextBoxPerformanceSummery.AppendText(e.Error.Message + "\r\nエラーが発生したので計算を中断します。");
            else if (e.Cancelled)
                this.richTextBoxPerformanceSummery.AppendText("中断されました。");
            else
                this.richTextBoxPerformanceSummery.AppendText((string)e.Result);

            // 各種操作を復旧する。
            this.buttonPerformance.Text = "計算";
            this.menuItemLogAllDelete.Enabled = true;
            if (this.ptFileTreeView.SelectedRelativeFile != null
                && this.comboBoxBrandList.SelectedItem != null)
            {
                this.buttonExecute.Enabled = true;
                this.menuItemLogDelete.Enabled = true;
                this.menuItemBrandListEdit.Enabled = true;
            }
            else
            {
                this.buttonPerformance.Enabled = false;
            }
            this.progressBarPerformance.Value = 0;
        }

        /// <summary>
        /// 選択されているシステムを取得します。
        /// </summary>
        /// <returns>選択されているシステムです。</returns>
        private TradingSystem GetSelectedSystem()
        {
            string file = this.ptFileTreeView.SelectedRelativeFile;
            if (file != null)
            {
                int mode = 0;
                if (this.radioButtonWeekly.Checked)
                    mode = 1;
                TradingSystem record = SystemTable.GetRecord(file, mode);
                if (record == null)
                    record = SystemTable.Add(file, mode);
                return record;
            }

            return null;
        }

        /// <summary>
        /// 選択されている対象銘柄のリストを取得します。
        /// </summary>
        /// <returns>選択されている対象銘柄のリストです。</returns>
        private Brand[] GetSelectedBrands()
        {
            object item = this.comboBoxBrandList.SelectedItem;
            if (item != null)
            {
                BrandList brandList = ((BrandListItem)item).BrandList;
                return brandList.Brands;
            }

            return null;
        }

        private void buttonHistory_Click(object sender, System.EventArgs e)
        {
            TradingSystem system = this.GetSelectedSystem();
            if (system == null)
                return;
            Brand[] brands = this.GetSelectedBrands();
            if (brands == null)
                return;

            SystemLog[] logs = SystemLogTable.GetRecords(system.Id,
                    this.dateTimePickerHistoryDateMin.Value,
                    this.dateTimePickerHistoryDateMax.Value);
            Hashtable brandIdTable = new Hashtable();
            foreach (Brand brand in brands)
                brandIdTable.Add(brand.Id, null);

            this.listViewHistory.Items.Clear();
            this.listViewHistory.BeginUpdate();
            foreach (SystemLog log in logs)
            {
                Brand brand = log.Brand;
                if (brandIdTable.ContainsKey(brand.Id))
                {
                    ListViewItem listViewItem = new ListViewItem(new string[]{
						log.Date.ToString("yy/MM/dd"),
						brand.Code.ToString(),
						brand.Name,
						log.Price.ToString(),
						log.Number.ToString(),
						log.Order == 0 ? "買" : "売" });
                    listViewItem.BackColor = log.Order == 0 ? Color.LightBlue : Color.LightPink;
                    this.listViewHistory.Items.Add(listViewItem);
                }
            }
            this.listViewHistory.EndUpdate();
        }

        private void copyHistory_Click(object sender, System.EventArgs e)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            foreach (ListViewItem item in this.listViewHistory.SelectedItems)
            {
                for (int n = 0; n < item.SubItems.Count; n++)
                {
                    builder.Append(item.SubItems[n].Text);
                    if (n < item.SubItems.Count - 1)
                        builder.Append(",");
                }
                builder.Append("\n");
            }
            if (builder.Length == 0)
                return;
            Clipboard.SetDataObject(builder.ToString());
        }
    }
}
