// Copyright(C) 2008 panacorn <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: KdbComUpdator.cs,v 1.1 2008-02-03 13:27:08 panacoran Exp $

using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Text;
using Protra.Lib.Db;

namespace Protra.Lib.Update
{
	/// <summary>
	/// 株価データダウンロードサイトを利用して株価データの更新を行うクラス。
	/// </summary>
	public class KdbComUpdator: PriceDataUpdator
	{
        /// <summary>
        /// データが存在する最初の日付を取得する。
        /// </summary>
        public static DateTime DataSince
        {
            get { return DateTime.Now.AddMonths(-6); }
        }

        /// <summary>
		/// 株価データを更新する。
		/// </summary>
		/// <param name="worker">BackgroundWorker</param>
        /// <param name="e">DoWorkイベントの引数</param>
		public override void Update(BackgroundWorker worker, DoWorkEventArgs e)
		{
            DateTime begin = (DateTime)e.Argument;
            if (begin < DataSince)
                begin = DataSince;
			DateTime today = DateTime.Now;
			// 新しいデータが置かれるのは早くても午後4時以降
			if (today.Hour < 16)
				today = today.AddDays(-1);

            for (Start(begin, today); ShouldContinue(); NextDate())
			{
				UpdateProgress(worker, e);

                StartDownload();
                DownloadUtil.Url =
                    "http://k-db.com/site/download.aspx?date=" +
                    Date.ToString(@"yyyyMMdd") + "&hyouji=1";
                Stream stream = DownloadUtil.GetResponse();
                if (stream == null)
                {
                    DecrementTotalDays();
                    continue;
                }
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    stream.Close();
                    return;
                }
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift_jis"));
                ArrayList dataList = new ArrayList();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    PriceData tmp = ParseLine(line);
                    if (tmp != null)
                    {
                        tmp.Date = Date; // 各レコードには日付がない。
                        dataList.Add(tmp);
                    }
                }
                reader.Close();
                TotalRecords = dataList.Count;
                EndDownload();

                for (; NumRecords < TotalRecords; IncrementRecords(), UpdateProgress(worker, e))
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        PriceTable.Delete(Date);
                        return;
                    }
                    
                    PriceData data = (PriceData)dataList[NumRecords];
                    Brand brand = BrandTable.GetRecordOrCreate(data.MarketId, data.Code, data.Name);
                    PriceTable.Add(brand.Id, data.Date, data.Open, data.High, data.Low, data.Close, data.Volume);
                }
                IncrementDays();
            }

			UpdateSplitData(worker, e);
            worker.ReportProgress(100, "");
		}

        /// <summary>
        /// 文字列に含まれるデータを格納したオブジェクトを返す。
        /// </summary>
        /// <param name="line">文字列を指定する。</param>
        /// <returns>オブジェクト</returns>
        private PriceData ParseLine(string line)
        {
            string[] tokens = line.Split(',');
            PriceData r = new PriceData();
            try
            {
                int i = 0;
				if (tokens[i] == "指数")
				{
					if (tokens[2] == "TOPIX")
						r.Code = 1002;
					else if (tokens[2] == "日経平均")
						r.Code = 1001;
					else
						return null;
				}
				else
					r.Code = int.Parse(tokens[i]);
				switch (tokens[++i])
				{
					case "":
						if (r.Code == 1001 || r.Code == 1002)
                            r.MarketId = Db.MarketId.Tokyo1;
						else
							return null;
						break;
					case "東証":
					case "東証１部":
						r.MarketId = Db.MarketId.Tokyo1;
						break;
					case "東証２部":
						r.MarketId = Db.MarketId.Tokyo2;
						break;
					case "東証マザーズ":
					case "東証マザーズ外国":
						r.MarketId = Db.MarketId.Mothers;
						break;
                    case "東証１部外国":
                        r.MarketId = MarketId.TokyoForeign;
                        break;
                    case "大証":
                    case "大証１部":
                        r.MarketId = MarketId.Osaka1;
                        break;
                    case "大証２部":
                        r.MarketId = MarketId.Osaka2;
                        break;
                    case "ＨＣ":
                        r.MarketId = MarketId.Hercules;
                        break;
                    case "名証":
                    case "名証１部":
                        r.MarketId = MarketId.Nagoya1;
                        break;
                    case "名証２部":
                        r.MarketId = MarketId.Nagoya2;
                        break;
                    case "ＪＱ":
                        r.MarketId = MarketId.Jasdaq;
                        break;
					default:
						return null;
                }
				r.Name = tokens[++i];
                r.Open = (int)ParseField(tokens[++i]);
                r.High = (int)ParseField(tokens[++i]);
                r.Low = (int)ParseField(tokens[++i]);
                r.Close = (int)ParseField(tokens[++i]);
                r.Volume = ParseField(tokens[++i]) / 1000;
            }
            catch (FormatException)
            {
                // フォーマットエラーは全部無視する。
                return null;
            }
            return r;
        }

		private double ParseField(string s)
		{
			// 無効なフィールドを示す"-"を0として扱う。
			if (s == "-")
				return 0;
			// 指数の値に小数が含まれているのでdouble.Parseを利用する。
			return double.Parse(s);
		}
	}
}
