// Copyright (C) 2004 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2004, 2005, 2007, 2010 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: EditBrandListContentDialog.cs 311 2010-03-21 12:44:47Z panacoran $

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Protra.Lib;
using Protra.Lib.Config;
using Protra.Lib.Db;

namespace PtSim.Dialogs
{
	/// <summary>
	/// 銘柄リストの内容を編集するためのダイアログです。
	/// </summary>
	public class EditBrandListContentDialog : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label labelName;
		private System.Windows.Forms.Label labelContent;
		private System.Windows.Forms.Label labelInfo;
		private System.Windows.Forms.TextBox textBoxName;
		private System.Windows.Forms.TextBox textBoxContent;
		private System.Windows.Forms.Button buttonOk;
		private System.Windows.Forms.Button buttonCancel;
		private System.Windows.Forms.GroupBox groupBoxCodeRange;
		private System.Windows.Forms.Label labelMarket;
		private System.Windows.Forms.Label labelCodeRange;
		private System.Windows.Forms.ComboBox comboBoxMarket;
		private System.Windows.Forms.TextBox textBoxCode1;
		private System.Windows.Forms.TextBox textBoxCode2;
		private System.Windows.Forms.Button buttonCodeRange;
		/// <summary>
		/// 必要なデザイナ変数です。
		/// </summary>
		private System.ComponentModel.Container components = null;

        private Protra.Lib.Config.BrandList selected;

        /// <summary>
        /// 選択されている銘柄リストを取得または設定する。
        /// </summary>
        public Protra.Lib.Config.BrandList SelectedList
        {
            get
            {
                return selected;
            }
            set
            {
                selected = value;
                StringBuilder sb = new StringBuilder();
                foreach (var id in value.List)
                {
                    var brand = BrandTable.GetRecordByNewId(id);
                    sb.Append(brand.Code + "." +(int)brand.MarketId + "\r\n");
                }
                Text = value.Name;
                textBoxName.Text = value.Name;
                textBoxContent.Text = sb.ToString();
            }
        }

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

            Text = "新規銘柄リスト";
            textBoxName.Text = "新規銘柄リスト";

            comboBoxMarket.Items.AddRange(
                new object[] { "東証1部", "東証2部", "マザーズ", "東証外国部",
                "大証1部", "大証2部", "ヘラクレス", "名証1部", "名証2部", "Jasdaq"});
			comboBoxMarket.SelectedIndex = 0;
		}

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

		#region Windows フォーム デザイナで生成されたコード 
		/// <summary>
		/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディタで変更しないでください。
		/// </summary>
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditBrandListContentDialog));
            this.labelName = new System.Windows.Forms.Label();
            this.labelContent = new System.Windows.Forms.Label();
            this.labelInfo = new System.Windows.Forms.Label();
            this.textBoxName = new System.Windows.Forms.TextBox();
            this.textBoxContent = new System.Windows.Forms.TextBox();
            this.buttonOk = new System.Windows.Forms.Button();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.comboBoxMarket = new System.Windows.Forms.ComboBox();
            this.labelMarket = new System.Windows.Forms.Label();
            this.groupBoxCodeRange = new System.Windows.Forms.GroupBox();
            this.buttonCodeRange = new System.Windows.Forms.Button();
            this.labelCodeRange = new System.Windows.Forms.Label();
            this.textBoxCode2 = new System.Windows.Forms.TextBox();
            this.textBoxCode1 = new System.Windows.Forms.TextBox();
            this.groupBoxCodeRange.SuspendLayout();
            this.SuspendLayout();
            // 
            // labelName
            // 
            this.labelName.Location = new System.Drawing.Point(8, 8);
            this.labelName.Name = "labelName";
            this.labelName.Size = new System.Drawing.Size(72, 16);
            this.labelName.TabIndex = 0;
            this.labelName.Text = "銘柄リスト名";
            // 
            // labelContent
            // 
            this.labelContent.Location = new System.Drawing.Point(8, 56);
            this.labelContent.Name = "labelContent";
            this.labelContent.Size = new System.Drawing.Size(32, 16);
            this.labelContent.TabIndex = 2;
            this.labelContent.Text = "内容";
            // 
            // labelInfo
            // 
            this.labelInfo.Location = new System.Drawing.Point(148, 28);
            this.labelInfo.Name = "labelInfo";
            this.labelInfo.Size = new System.Drawing.Size(160, 240);
            this.labelInfo.TabIndex = 4;
            this.labelInfo.Text = resources.GetString("labelInfo.Text");
            // 
            // textBoxName
            // 
            this.textBoxName.Location = new System.Drawing.Point(8, 24);
            this.textBoxName.Name = "textBoxName";
            this.textBoxName.Size = new System.Drawing.Size(128, 19);
            this.textBoxName.TabIndex = 1;
            // 
            // textBoxContent
            // 
            this.textBoxContent.AcceptsReturn = true;
            this.textBoxContent.Location = new System.Drawing.Point(8, 72);
            this.textBoxContent.Multiline = true;
            this.textBoxContent.Name = "textBoxContent";
            this.textBoxContent.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBoxContent.Size = new System.Drawing.Size(128, 228);
            this.textBoxContent.TabIndex = 3;
            // 
            // buttonOk
            // 
            this.buttonOk.Location = new System.Drawing.Point(148, 276);
            this.buttonOk.Name = "buttonOk";
            this.buttonOk.Size = new System.Drawing.Size(75, 23);
            this.buttonOk.TabIndex = 5;
            this.buttonOk.Text = "OK";
            this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
            // 
            // buttonCancel
            // 
            this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancel.Location = new System.Drawing.Point(228, 276);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 6;
            this.buttonCancel.Text = "キャンセル";
            // 
            // comboBoxMarket
            // 
            this.comboBoxMarket.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxMarket.Location = new System.Drawing.Point(52, 20);
            this.comboBoxMarket.Name = "comboBoxMarket";
            this.comboBoxMarket.Size = new System.Drawing.Size(88, 20);
            this.comboBoxMarket.TabIndex = 1;
            // 
            // labelMarket
            // 
            this.labelMarket.Location = new System.Drawing.Point(16, 24);
            this.labelMarket.Name = "labelMarket";
            this.labelMarket.Size = new System.Drawing.Size(32, 16);
            this.labelMarket.TabIndex = 0;
            this.labelMarket.Text = "市場";
            // 
            // groupBoxCodeRange
            // 
            this.groupBoxCodeRange.Controls.Add(this.buttonCodeRange);
            this.groupBoxCodeRange.Controls.Add(this.labelCodeRange);
            this.groupBoxCodeRange.Controls.Add(this.textBoxCode2);
            this.groupBoxCodeRange.Controls.Add(this.textBoxCode1);
            this.groupBoxCodeRange.Controls.Add(this.comboBoxMarket);
            this.groupBoxCodeRange.Controls.Add(this.labelMarket);
            this.groupBoxCodeRange.Location = new System.Drawing.Point(312, 20);
            this.groupBoxCodeRange.Name = "groupBoxCodeRange";
            this.groupBoxCodeRange.Size = new System.Drawing.Size(152, 108);
            this.groupBoxCodeRange.TabIndex = 7;
            this.groupBoxCodeRange.TabStop = false;
            this.groupBoxCodeRange.Text = "コード範囲から入力";
            // 
            // buttonCodeRange
            // 
            this.buttonCodeRange.Location = new System.Drawing.Point(92, 76);
            this.buttonCodeRange.Name = "buttonCodeRange";
            this.buttonCodeRange.Size = new System.Drawing.Size(48, 24);
            this.buttonCodeRange.TabIndex = 5;
            this.buttonCodeRange.Text = "入力";
            this.buttonCodeRange.Click += new System.EventHandler(this.buttonCodeRange_Click);
            // 
            // labelCodeRange
            // 
            this.labelCodeRange.Location = new System.Drawing.Point(68, 52);
            this.labelCodeRange.Name = "labelCodeRange";
            this.labelCodeRange.Size = new System.Drawing.Size(20, 16);
            this.labelCodeRange.TabIndex = 3;
            this.labelCodeRange.Text = "〜";
            // 
            // textBoxCode2
            // 
            this.textBoxCode2.Location = new System.Drawing.Point(92, 48);
            this.textBoxCode2.Name = "textBoxCode2";
            this.textBoxCode2.Size = new System.Drawing.Size(48, 19);
            this.textBoxCode2.TabIndex = 4;
            this.textBoxCode2.Text = "9999";
            // 
            // textBoxCode1
            // 
            this.textBoxCode1.Location = new System.Drawing.Point(16, 48);
            this.textBoxCode1.Name = "textBoxCode1";
            this.textBoxCode1.Size = new System.Drawing.Size(48, 19);
            this.textBoxCode1.TabIndex = 2;
            this.textBoxCode1.Text = "0";
            // 
            // EditBrandListContentDialog
            // 
            this.AcceptButton = this.buttonOk;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.CancelButton = this.buttonCancel;
            this.ClientSize = new System.Drawing.Size(474, 309);
            this.ControlBox = false;
            this.Controls.Add(this.groupBoxCodeRange);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.buttonOk);
            this.Controls.Add(this.textBoxContent);
            this.Controls.Add(this.textBoxName);
            this.Controls.Add(this.labelInfo);
            this.Controls.Add(this.labelContent);
            this.Controls.Add(this.labelName);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "EditBrandListContentDialog";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "EditBrandListContentDialog";
            this.groupBoxCodeRange.ResumeLayout(false);
            this.groupBoxCodeRange.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private void buttonOk_Click(object sender, System.EventArgs e)
		{
			if (textBoxName.Text == "") 
			{
				MessageBox.Show("銘柄リスト名を入力してください。");
				textBoxName.Focus();
				return;
			}

            foreach (var bl in GlobalEnv.BrandListConfig.List)
            {
                if (bl.Name == textBoxName.Text && bl != selected)
                {
                    MessageBox.Show("銘柄リスト名が重複しています。");
                    textBoxName.Focus();
                    return;
                }
            }

            var brandIdTable = new Dictionary<string, object>();
			string[] lines = this.textBoxContent.Lines;
			foreach (string line in lines) 
			{
				string l = line.Trim();
				if (line == "")
					continue;
				string[] fields = l.Split('.');
				try
				{
					if (fields.Length == 1) 
					{
						// 銘柄コードのみの指定。最小の市場コードを持つ銘柄が選ばれる。
						int code = int.Parse(fields[0]);
						var brands = BrandTable.GetRecords(code);
						if (brands.Length == 0)
						{
							MessageBox.Show("存在しない銘柄です: " + line);
							return;
						}
						brandIdTable[brands[0].NewId] = null;
					}
					else if(fields.Length == 2)
					{
						// 銘柄コードと市場コードの指定。
						var brand = BrandTable.GetRecord((MarketId)int.Parse(fields[1]), int.Parse(fields[0]));
						if (brand == null)
						{
							MessageBox.Show("存在しない銘柄です: " + line);
							return;
						}
						brandIdTable[brand.NewId] = null;
					}
					else 
					{
						throw new FormatException();
					}
				}
				catch(FormatException)
				{
					MessageBox.Show("フォーマットエラーです: " + line);
					return;
				}
			}

			if (selected == null) // 追加
            {
                selected = new Protra.Lib.Config.BrandList();
                selected.Name = textBoxName.Text;
                GlobalEnv.BrandListConfig.List.Add(selected);
            }
			else // 編集
				selected.Name = textBoxName.Text;

            selected.List.Clear();
			foreach(var newId in brandIdTable.Keys)
				selected.List.Add(newId);
            selected.List.Sort();

			DialogResult = DialogResult.OK;
            GlobalEnv.BrandListConfig.Save();
		}

		private void buttonCodeRange_Click(object sender, System.EventArgs e)
		{
			try
			{
				Market market = MarketTable.GetRecord((MarketId)(this.comboBoxMarket.SelectedIndex + 1));
				int code1 = int.Parse(this.textBoxCode1.Text);
				int code2 = int.Parse(this.textBoxCode2.Text);
				StringBuilder sb = new StringBuilder();
				Brand[] brands = BrandTable.GetRecords(market.Id, code1, code2);
				foreach (Brand brand in brands)
					sb.Append(brand.Code + "." + (int)brand.MarketId + "\r\n");
				this.textBoxContent.AppendText(sb.ToString());
			}
			catch(FormatException)
			{
			}
		}
	}
}
