using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VICrawlerNS
{
	public partial class VICrawler : MaterialForm
	{
		class ITEM
		{
			public int m_iSeq;
			public string m_strCode;
			public string m_strCodeName;
			public uint m_uiEventCode;
			public string m_strDesc;

			public DateTime m_RecevedTime;

			public int m_iStartPrice = 0;
			public int m_iLowPrice = 10000000;
			public float m_fLowP = 0.0f;
			public int m_iHighPrice = 0;
			public float m_fHighP = 0.0f;
		}

		CybosHelper m_CybosHelper = null;
		List<ITEM> m_ItemList = new List<ITEM>();
		List<PriceCheck> m_PriceCheckList = new List<PriceCheck>();
		CodeList m_CodeList = new CodeList();
		ExcelHandler m_Excel = new ExcelHandler(Util.GetLogPath()+"/PriceCheck-"+DateTime.Now.ToString("yyyy-MM-dd")+".xlsx",
			new string[] { "Seq", "받은 시간", "종목코드", "종목명", "코드", "신호", "시가", "저가", "대비", "고가", "대비" });
		System.Timers.Timer m_SystemTimer = new System.Timers.Timer();

		public VICrawler()
		{
			InitializeComponent();
			lvItems.ListViewItemSorter = new ListViewItemComparer(chSeq.Index, SortOrder.Ascending);
			lvItems.Sorting = SortOrder.Ascending;

			Util.SetLogView(tbLog);
			Config.Init();

			tbCheckTime.Text = Config.GetCheckTime().ToString();

			cbAccount.Items.Add(Config.GetAccount());
			cbAccount.SelectedItem = Config.GetAccount();
			tbSubAccount.Text = Config.GetSubAccount();

			m_CybosHelper = new CybosHelper(this);

			var materialSkinManager = MaterialSkinManager.Instance;
			materialSkinManager.AddFormToManage(this);
			materialSkinManager.Theme = MaterialSkinManager.Themes.DARK;
			materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);

			m_SystemTimer.Interval = 100;
			m_SystemTimer.Elapsed += SystemTimer_Elapsed;
			m_SystemTimer.Start();
		}

		private void SystemTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			if(lbInfo.InvokeRequired)
			{
				lbInfo.Invoke(new Action(() => {
				lbInfo.Text = string.Format("{0} | {1} | {2}",
					m_CybosHelper.GetLimitRemainCountRQ(),
					m_CybosHelper.GetLimitRemainCountSB(),
					DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
				}));

				//lbInfo.Location = new Point(lbInfo.Parent.Width-lbInfo.Width, lbInfo.Top);
			}
			else
			{
				lbInfo.Text = string.Format("{0} | {1}",
					m_CybosHelper.GetLimitRemainCountRQ(),
					m_CybosHelper.GetLimitRemainCountSB(),
					DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

				//lbInfo.Location = new Point(lbInfo.Parent.Width-lbInfo.Width, lbInfo.Top);
			}

			m_PriceCheckList.RemoveAll(s => s.IsEnd());
		}

		public void SetAccountList(string[] aAccountList)
		{
			cbAccount.Items.Clear();
			cbAccount.Items.AddRange(aAccountList);
		}

		private void btCybos_Click(object sender, EventArgs e)
		{
			m_CybosHelper.InitCybos();

			btCybos.Primary = false;
			btCybos.Enabled = false;
		}

		public void OnReceivedEvent(uint uiTime, string strCode, uint uiEventCode, string strDesc, bool bUp)
		{
			int iSeq = lvItems.Items.Count+1;

			CodeList.CODE_VALUE Code = m_CodeList.GetCode(strCode);

			ITEM Item = new ITEM();
			Item.m_iSeq = iSeq;
			Item.m_strCode = strCode;
			Item.m_strCodeName = Code.m_strName;
			Item.m_uiEventCode = uiEventCode;
			Item.m_strDesc = strDesc;
			Item.m_RecevedTime = DateTime.Now;
			Item.m_iStartPrice = 0;
			m_ItemList.Add(Item);

			if(lvItems.InvokeRequired)
			{
				lvItems.Invoke(new Action(() => {
					lvItems.Items.Add(new ListViewItem(new string[]
					{
						iSeq.ToString(),
						string.Format("{0:00}:{1:00}:{2:00}", uiTime/10000, (uiTime%10000)/100, uiTime%100),
						Item.m_RecevedTime.ToString("hh:mm:ss.fff"),
						strCode,
						Item.m_strCodeName,
						uiEventCode.ToString(),
						strDesc,
						"",
						"",
						"",
						"",
						""
					}));
					lvItems.Items[lvItems.Items.Count-1].UseItemStyleForSubItems = false;
				}));
			}
			else
			{
				lvItems.Items.Add(new ListViewItem(new string[]
					{
						iSeq.ToString(),
						string.Format("{0:00}:{1:00}:{2:00}", uiTime/10000, (uiTime%10000)/100, uiTime%100),
						Item.m_RecevedTime.ToString("hh:mm:ss.fff"),
						strCode,
						Item.m_strCodeName,
						uiEventCode.ToString(),
						strDesc,
						"",
						"",
						"",
						"",
						""
					}));
				lvItems.Items[lvItems.Items.Count-1].UseItemStyleForSubItems = false;
			}

			if((uiEventCode == 755 || uiEventCode == 757) /*&& bUp == true*/)
				m_CybosHelper.Buy(Code, Config.GetBuyPrice());

			m_PriceCheckList.Add(new PriceCheck(iSeq, strCode, Code.m_strName, this, Config.GetCheckTime()*60));

			Util.Log(Util.LOG_TYPE.VERVOSE, string.Format("{0} / {1} / {2} / {3}",
				uiTime, strCode, uiEventCode, strDesc));
		}

		public void OnReceivedStartPrice(int iSeq, int iStartPrice)
		{
			var Item = lvItems.Items.Cast<ListViewItem>().FirstOrDefault(s => s.SubItems[chSeq.Index].Text == iSeq.ToString());
			if(Item == default(ListViewItem))
				return;

			if(lvItems.InvokeRequired)
			{
				lvItems.Invoke(new Action(() => {
					Item.SubItems[chStartPrice.Index].Text = string.Format("{0:n0}", iStartPrice);
				}));
			}
			else
			{
				Item.SubItems[chStartPrice.Index].Text = string.Format("{0:n0}", iStartPrice);
			}
		}

		public void OnPriceCheckEnd(int iSeq, int iStartPrice, int iLowPrice, float fLowP, int iHighPrice, float fHighP)
		{
			if(lvItems.InvokeRequired)
			{
				lvItems.Invoke(new Action(() => {
					var Item = lvItems.Items.Cast<ListViewItem>().FirstOrDefault(s => s.SubItems[chSeq.Index].Text == iSeq.ToString());
					if(Item == default(ListViewItem))
						return;

					Item.SubItems[chStartPrice.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
					Item.SubItems[chLowPrice.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
					Item.SubItems[chLowP.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
					Item.SubItems[chHighPrice.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
					Item.SubItems[chHighP.Index].BackColor = Color.FromArgb(255, 245, 245, 245);

					if(iHighPrice > 0)
					{
						Item.SubItems[chLowPrice.Index].Text = string.Format("{0:n0}", iLowPrice);
						Item.SubItems[chLowPrice.Index].ForeColor = (iLowPrice > iStartPrice) ? Color.Red : (iLowPrice < iStartPrice) ? Color.Blue : Color.Black;
						Item.SubItems[chLowP.Index].Text = string.Format("{0:n2}", (fLowP-1.0f)*100);
						Item.SubItems[chLowP.Index].ForeColor = (fLowP > 1.0f) ? Color.Red : (fLowP < 1.0f) ? Color.Blue : Color.Black;
						Item.SubItems[chHighPrice.Index].Text = string.Format("{0:n0}", iHighPrice);
						Item.SubItems[chHighPrice.Index].ForeColor = (iHighPrice > iStartPrice) ? Color.Red : (iHighPrice < iStartPrice) ? Color.Blue : Color.Black;
						Item.SubItems[chHighP.Index].Text = string.Format("{0:n2}", (fHighP-1.0f)*100);
						Item.SubItems[chHighP.Index].ForeColor = (fHighP > 1.0f) ? Color.Red : (fHighP < 1.0f) ? Color.Blue : Color.Black;
					}
				}));
			}
			else
			{
				var Item = lvItems.Items.Cast<ListViewItem>().FirstOrDefault(s => s.SubItems[chSeq.Index].Text == iSeq.ToString());
				if(Item == default(ListViewItem))
					return;

				Item.SubItems[chStartPrice.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
				Item.SubItems[chLowPrice.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
				Item.SubItems[chLowP.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
				Item.SubItems[chHighPrice.Index].BackColor = Color.FromArgb(255, 245, 245, 245);
				Item.SubItems[chHighP.Index].BackColor = Color.FromArgb(255, 245, 245, 245);

				if(iHighPrice > 0)
				{
					Item.SubItems[chLowPrice.Index].Text = string.Format("{0:n0}", iLowPrice);
					Item.SubItems[chLowPrice.Index].ForeColor = (iLowPrice > iStartPrice) ? Color.Red : (iLowPrice < iStartPrice) ? Color.Blue : Color.Black;
					Item.SubItems[chLowP.Index].Text = string.Format("{0:n2}", (fLowP-1.0f)*100);
					Item.SubItems[chLowP.Index].ForeColor = (fLowP > 1.0f) ? Color.Red : (fLowP < 1.0f) ? Color.Blue : Color.Black;
					Item.SubItems[chHighPrice.Index].Text = string.Format("{0:n0}", iHighPrice);
					Item.SubItems[chHighPrice.Index].ForeColor = (iHighPrice > iStartPrice) ? Color.Red : (iHighPrice < iStartPrice) ? Color.Blue : Color.Black;
					Item.SubItems[chHighP.Index].Text = string.Format("{0:n2}", (fHighP-1.0f)*100);
					Item.SubItems[chHighP.Index].ForeColor = (fHighP > 1.0f) ? Color.Red : (fHighP < 1.0f) ? Color.Blue : Color.Black;
				}
			}

			{
				ITEM Item = m_ItemList.Find(s => s.m_iSeq == iSeq);
				m_Excel.AddRow(new object[] { iSeq, Item.m_RecevedTime, Item.m_strCode, Item.m_strCodeName, Item.m_uiEventCode, Item.m_strDesc,
					iStartPrice, iLowPrice, fLowP, iHighPrice, fHighP});
			}
		}

		private void lvItems_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			SortOrder Order = (lvItems.Sorting == SortOrder.Descending || lvItems.Sorting == SortOrder.None) ? SortOrder.Ascending : SortOrder.Descending;

			lvItems.ListViewItemSorter = new ListViewItemComparer(e.Column, Order);
			lvItems.Sorting = Order;
			lvItems.Sort();
		}

		private void btApply_Click(object sender, EventArgs e)
		{
			Config.SetAccount((string)cbAccount.SelectedItem, tbSubAccount.Text);

			int iCheckTime;
			bool bParsed = int.TryParse(tbCheckTime.Text, out iCheckTime);
			if(bParsed == true)
				Config.SetCheckTime(iCheckTime);
		}

		private void materialFlatButton1_Click(object sender, EventArgs e)
		{
			var Code = m_CodeList.GetCode("A095300");
			m_CybosHelper.Buy(Code, 1000000);
		}
	}

	class ListViewItemComparer : IComparer
	{
		int m_iColumn = 0;
		SortOrder m_Order = SortOrder.Ascending;

		public ListViewItemComparer(int column, SortOrder Order)
		{
			m_iColumn = column;
			m_Order = Order;
		}

		public int Compare(object x, object y)
		{
			ListViewItem item1 = (ListViewItem)x;
			ListViewItem item2 = (ListViewItem)y;

			double num1;
			double num2;
			if(double.TryParse(item1.SubItems[m_iColumn].Text, out num1) &&
				double.TryParse(item2.SubItems[m_iColumn].Text, out num2))
			{
				return (num1>num2) ? 1 : -1;
			}
			else
			{
				if(m_Order == SortOrder.Ascending)
					return string.Compare(item1.SubItems[m_iColumn].Text, item2.SubItems[m_iColumn].Text);
				else
					return string.Compare(item2.SubItems[m_iColumn].Text, item1.SubItems[m_iColumn].Text);
			}
		}
	}
}
