using DSCBO1Lib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VICrawlerNS
{
	public class PriceCheck
	{
		int m_iSeq;
		string m_strCode;
		string m_strCodeName;
		int m_iStartPrice = int.MinValue;
		int m_iLowPrice = int.MaxValue;
		float m_fLowP = float.MaxValue;
		int m_iHighPrice = int.MinValue;
		float m_fHighP = float.MinValue;
		int m_iCurPrice = int.MinValue;

		DateTime m_StartTime;
		DateTime m_EndTime;

		StockCur m_StockCur = new StockCur();
		VICrawler m_Listener = null;
		bool m_bEnd = false;

		bool m_bCancel = true;
		int m_iCheckTimeInSec;

		System.Timers.Timer m_Timer = new System.Timers.Timer();

		public PriceCheck(int iSeq, string strCode, string strCodeName, VICrawler Listener, int iTimeInSec)
		{
			m_iSeq = iSeq;
			m_strCode = strCode;
			m_strCodeName = strCodeName;

			m_Listener = Listener;

			m_StartTime = DateTime.Now;
			m_EndTime = m_StartTime + TimeSpan.FromSeconds(iTimeInSec);

			m_StockCur.SetInputValue(0, strCode);
			m_StockCur.Received += StockCur_Received;
			m_StockCur.Subscribe();

			m_iCheckTimeInSec = iTimeInSec;
			m_bCancel = true;
			m_Timer.Interval = 10*1000;
			m_Timer.Elapsed += Timer_Elapsed;
			m_Timer.Start();
		}

		private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			if(m_bCancel == true)
			{
				if(m_iStartPrice < 0)
				{
					Stop();
				}
				else
				{
					m_Timer.Stop();
					m_Timer.Interval = (m_iCheckTimeInSec-10)*1000;
					m_Timer.Start();
				}

				m_bCancel = false;
			}
			else
			{
				Stop();
			}
		}

		public bool IsEnd()
		{
			return m_bEnd;
		}

		private void Stop()
		{
			m_Listener.OnPriceCheckEnd(m_iSeq, m_iStartPrice, m_iLowPrice, m_fLowP, m_iHighPrice, m_fHighP);
			m_StockCur.Unsubscribe();
			m_bEnd = true;
		}

		private void StockCur_Received()
		{
			m_iCurPrice = m_StockCur.GetHeaderValue(13);
			if(m_iStartPrice == int.MinValue)
			{
				m_iStartPrice = m_iCurPrice;
				m_Listener.OnReceivedStartPrice(m_iSeq, m_iStartPrice);
			}

			m_iLowPrice = Math.Min(m_iLowPrice, m_iCurPrice);
			m_fLowP = m_iLowPrice/(float)m_iStartPrice;
			m_iHighPrice = Math.Max(m_iHighPrice, m_iCurPrice);
			m_fHighP = m_iHighPrice/(float)m_iStartPrice;
		}

		public override string ToString()
		{
			return string.Format("[{0}] {1:n0}({2:n0} | {3:n0} | {4:n0})", m_strCodeName, m_iCurPrice, m_iStartPrice, m_iLowPrice, m_iHighPrice);
		}
	}
}
