// Copyright(C) 2008, 2010 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 321 2010-03-29 11:37:51Z panacoran $

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using Protra.Lib.Data;

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

        /// <summary>
        /// 新しいデータが置かれる時刻に達しているか。
        /// </summary>
        /// <param name="time">時刻</param>
        /// <returns></returns>
        protected override bool IsDataAvailable(DateTime time)
        {
            return time.Hour >= 16;
        }

        /// <summary>
        /// データのURLを取得する。
        /// </summary>
        /// <returns>URL</returns>
        protected override string DownloadUrl()
        {
            return "http://k-db.com/site/download.aspx?date=" +
                    Date.ToString(@"yyyy-MM-dd-\d");
        }

        private Dictionary<DateTime, double> indexVolume;

        /// <summary>
		/// 株価データを更新する。
		/// </summary>
		/// <param name="worker">BackgroundWorker</param>
        /// <param name="e">DoWorkイベントの引数</param>
		protected override void UpdatePrice(BackgroundWorker worker, DoWorkEventArgs e)
		{
            indexVolume = GetIndexVolume();
            base.UpdatePrice(worker, e);
		}

        Dictionary<DateTime, double> GetIndexVolume()
        {
            DownloadUtil.Url = "http://k-db.com/site/toukei.aspx?market=T1&download=csv";
            Stream stream = DownloadUtil.GetResponse();
            if (stream == null)
                throw new ApplicationException("市場統計データの読み込みに失敗しました。");
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift_jis"));
            string line;
            Dictionary<DateTime, Double> indexVolume = new Dictionary<DateTime, double>();
            while ((line = reader.ReadLine()) != null)
            {
                string[] tokens = line.Split(',');
                if ((tokens[0] == "東証１部") || (tokens[0] == "日付"))
                    continue;
                DateTime date = DateTime.ParseExact(tokens[0], "yyyy年MM月dd日", null);
                double volume = Math.Round(double.Parse(tokens[1]) / 1000, MidpointRounding.AwayFromZero);
                indexVolume[date] = volume;
            }
            reader.Close();
            return indexVolume;
        }

        /// <summary>
        /// 文字列に含まれるデータを格納したオブジェクトを返す。
        /// </summary>
        /// <param name="line">文字列を指定する。</param>
        /// <returns>オブジェクト</returns>
        protected override Price ParseLine(string line)
        {
            string[] tokens = line.Split(',');
            Price r = new Price();
            try
            {
                if (tokens[0] == "指数")
                {
                    if (tokens[2] == "TOPIX")
                    {
                        r.Code = "1002";
                        r.Volume = indexVolume[Date];
                    }
                    else if (tokens[2] == "日経平均")
                    {
                        r.Code = "1001";
                        r.Volume = indexVolume[Date];
                    }
                    else
                        return null;
                }
                else
                    r.Code = tokens[0];
				switch (tokens[1])
				{
					case "":
                        if (r.Code == "1001" || r.Code == "1002")
                            r.Market = "T1";
                        else
                            return null;
						break;
					case "東証":
					case "東証１部":
						r.Market = "T1";
						break;
					case "東証２部":
                        r.Market = "T2";
						break;
					case "東証マザーズ":
					case "東証マザーズ外国":
						r.Market = "M";
						break;
                    case "東証１部外国":
                        r.Market = "T1";
                        break;
                    case "大証":
                    case "大証１部":
                        r.Market = "O1";
                        break;
                    case "大証２部":
                        r.Market = "O2";
                        break;
                    case "ＨＣスタンダード":
                    case "ＨＣスタンダード外国":
                    case "ＨＣグロース":
                        r.Market = "H";
                        break;
                    case "ＪＱ":
                    case "ＪＱＮＥＯ":
                        r.Market = "J";
                        break;
					default:
						return null;
                }
                r.Date = Date;
                r.Open = (int)ParseField(tokens[4]);
                r.High = (int)ParseField(tokens[5]);
                r.Low = (int)ParseField(tokens[6]);
                r.Close = (int)ParseField(tokens[7]);
                if (r.Volume == 0)
                    r.Volume = ParseField(tokens[8]) / 1000;
            }
            catch (FormatException)
            {
                // フォーマットエラーは全部無視する。
                return null;
            }
            return r;
        }

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