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

namespace NewsCrawler
{
	public class CybosHelper
	{
		CPUTILLib.CpCybos m_CPCybos = new CPUTILLib.CpCybos();
		CPFORETRADELib.CpForeTdUtil m_CPUtil = new CPFORETRADELib.CpForeTdUtil();
		DSCBO1Lib.StockMst m_CPStockMst = new DSCBO1Lib.StockMst();
		CPTRADELib.CpTd0311 m_CP0311 = new CPTRADELib.CpTd0311();
		bool m_bInitialized = false;

		public CybosHelper()
		{
			short iResult = m_CPUtil.TradeInit();
			switch(iResult)
			{
				case -1:
					Util.Log(Util.LOG_TYPE.ERROR, "[TradeInit] 오류");
					break;

				case 0:
					m_bInitialized = true;
					Util.Log(Util.LOG_TYPE.VERVOSE, "[TradeInit] 로그인 되었습니다");
					break;

				case 1:
					Util.Log(Util.LOG_TYPE.ERROR, "[TradeInit] 업무 키 입력 잘못됨");
					break;

				case 2:
					Util.Log(Util.LOG_TYPE.ERROR, "[TradeInit] 계좌 비밀번호가 잘못되었습니다");
					break;

				case 3:
					Util.Log(Util.LOG_TYPE.ERROR, "[TradeInit] 취소되었습니다");
					break;
			}
		}

		public string[] GetAccounts()
		{
			return m_CPUtil.AccountNumber;
		}

		public int GetLimitRemainCountTrace()
		{
			return m_CPCybos.GetLimitRemainCount(CPUTILLib.LIMIT_TYPE.LT_TRADE_REQUEST);
		}

		public int GetLimitRemainCountRQ()
		{
			return m_CPCybos.GetLimitRemainCount(CPUTILLib.LIMIT_TYPE.LT_NONTRADE_REQUEST);
		}

		public int GetLimitRemainCountSB()
		{
			return m_CPCybos.GetLimitRemainCount(CPUTILLib.LIMIT_TYPE.LT_SUBSCRIBE);
		}

		public bool IsConnected()
		{
			return (m_CPCybos.IsConnect==1);
		}

		public void Buy(CodeList.CODE_VALUE Code, int iMaxPrice)
		{
			if(m_bInitialized == false)
			{
				Util.Log(Util.LOG_TYPE.ERROR, "[Buy] 매수 준비가 되지 않았습니다");
				return;
			}

			m_CPStockMst.SetInputValue(0, Code.m_strCode);
			m_CPStockMst.BlockRequest2(0);
			int iCurPrice = m_CPStockMst.GetHeaderValue(13);

			int iCount = iMaxPrice/iCurPrice;

			m_CP0311.SetInputValue(0, 2);
			m_CP0311.SetInputValue(1, Config.GetAccount());
			m_CP0311.SetInputValue(2, Config.GetSubAccount());
			m_CP0311.SetInputValue(3, Code.m_strCode);
			m_CP0311.SetInputValue(4, iCount);
			m_CP0311.SetInputValue(5, 0);
			m_CP0311.SetInputValue(7, "0");
			m_CP0311.SetInputValue(8, "03");
			m_CP0311.BlockRequest2(0);

			Util.Log(Util.LOG_TYPE.BUY, string.Format("code:{0} {1}주 현재가 {2}원, 시장가 매수", Code.ToString(), iCount, iCurPrice));
		}
	}
}
