// Copyright (C) 2004 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2004, 2005, 2007, 2010, 2014 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 503 2014-02-10 06:10:07Z panacoran $

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Protra.Lib.Config;
using Protra.Lib.Data;

namespace Protra.Lib.Dialogs
{
    /// <summary>
    /// 銘柄リストの内容を編集するダイアログ
    /// </summary>
    public partial class EditBrandListContentDialog : Form
    {
        private BrandList _selected;

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public EditBrandListContentDialog()
        {
            InitializeComponent();

            textBoxName.Text = Text = "新規銘柄リスト";
            checkBoxObsolete.Checked = GlobalEnv.BrandListConfig.EnableObsoleteBrand;
            SetComboBoxMarket();
        }

        private void SetComboBoxMarket()
        {
            comboBoxMarket.BeginUpdate();
            comboBoxMarket.Items.Clear();
            // ReSharper disable CoVariantArrayConversion
            comboBoxMarket.Items.AddRange(checkBoxObsolete.Checked ? Market.AllNames : Market.Names);
            // ReSharper restore CoVariantArrayConversion
            comboBoxMarket.SelectedIndex = 0;
            comboBoxMarket.EndUpdate();
        }

        /// <summary>
        /// 選択されている銘柄リストを取得または設定する。
        /// </summary>
        public BrandList SelectedList
        {
            get { return _selected; }
            set
            {
                _selected = value;
                textBoxName.Text = Text = value.Name;
                textBoxList.Text = string.Join("\r\n", value.List.ToArray()) + "\r\n";
            }
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (textBoxName.Text == "")
            {
                using (new CenteredDialogHelper())
                    MessageBox.Show(this, "銘柄リスト名を入力してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBoxName.Focus();
                return;
            }
            foreach (var brandList in GlobalEnv.BrandListConfig.List)
            {
                if (brandList.Name != textBoxName.Text || brandList == _selected)
                    continue;
                using (new CenteredDialogHelper())
                    MessageBox.Show(this, "銘柄リスト名が重複しています。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBoxName.Focus();
                return;
            }
            var codeTable = new SortedDictionary<string, bool>();
            var obsTable = new SortedDictionary<string, string>();
            foreach (var line in textBoxList.Lines)
            {
                var code = line.Trim();
                if (code == "")
                    continue;
                var brand = GlobalEnv.BrandData[code];
                if (brand.Unit == 0)
                {
                    using (new CenteredDialogHelper())
                        MessageBox.Show(this, "存在しない銘柄です: " + code, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if ((brand.Flags & Brand.Flag.OBS) != 0)
                    obsTable[code] = brand.ToString();
                codeTable[code] = true;
            }
            if (!checkBoxObsolete.Checked && obsTable.Count != 0)
            {
                using (var dialog = new ObsoleteBrandDialog())
                {
                    dialog.ObsoleteList = string.Join("\r\n", new List<string>(obsTable.Values).ToArray());
                    var result = dialog.ShowDialog(this);
                    if (result == DialogResult.Cancel)
                        return;
                    if (result == DialogResult.Yes) // 削除
                    {
                        foreach (var code in obsTable.Keys)
                            codeTable.Remove(code);
                        textBoxList.Text = string.Join("\r\n", new List<string>(codeTable.Keys).ToArray()) + "\r\n";
                        return;
                    }
                }
            }
            if (_selected == null) // 追加
            {
                _selected = new BrandList {Name = textBoxName.Text};
                GlobalEnv.BrandListConfig.List.Add(_selected);
            }
            else // 編集
            {
                _selected.Name = textBoxName.Text;
            }
            _selected.List.Clear();
            _selected.List.AddRange(codeTable.Keys);
            GlobalEnv.BrandListConfig.EnableObsoleteBrand = checkBoxObsolete.Checked;
            DialogResult = DialogResult.OK;
            GlobalEnv.BrandListConfig.Save();
        }

        private void buttonCodeInput_Click(object sender, EventArgs e)
        {
            try
            {
                var codes = checkBoxObsolete.Checked ? Market.AllCodes : Market.Codes;
                var market = codes[comboBoxMarket.SelectedIndex];
                var first = int.Parse(textBoxCodeFirst.Text);
                var last = int.Parse(textBoxCodeLast.Text);
                var list = new List<string>();
                for (var i = first; i <= last; i++)
                {
                    var b = GlobalEnv.BrandData[i.ToString("D4")];
                    if (b.Unit == 0 || b.Market != market ||
                        !checkBoxObsolete.Checked && (b.Flags & Brand.Flag.OBS) != 0)
                        continue;
                    list.Add(b.Code);
                }
                textBoxList.AppendText(String.Join("\r\n", list.ToArray()) + "\r\n");
            }
            catch (FormatException)
            {
            }
        }

        private void checkBoxObsolete_CheckedChanged(object sender, EventArgs e)
        {
            SetComboBoxMarket();
        }
    }
}