using System;
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;
using WeifenLuo.WinFormsUI.Docking;

namespace friction
{
	public partial class PanelCompatibility : DockContent
	{
		MainForm m_Owner = null;

		public PanelCompatibility(MainForm owner)
		{
			InitializeComponent();

			m_Owner = owner;

			Theme.Apply(this);
			Theme.Apply(dgvMap);

			dgvMap.CellPainting += DgvMap_CellPainting;
			dgvMap.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
			dgvMap.ColumnHeadersHeight = 100;
			dgvMap.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
			dgvMap.DefaultCellStyle.Format = "N2";
		}

		public void UpdateData(DataHandler data)
		{
			var Springs = data.GetSpringList();
			var Tables = data.GetTableList();

			dgvMap.Rows.Clear();
			dgvMap.Columns.Clear();


			foreach (var table in Tables)
			{
				int iCol = dgvMap.Columns.Add(table, table);
				dgvMap.Columns[iCol].Width = 29;
			}

			foreach (var spring in Springs)
			{
				int iRow = dgvMap.Rows.Add();
				dgvMap.Rows[iRow].HeaderCell.Value = spring;

				var Averages = data.GetAvgAll(spring);
				foreach(var avg in Averages)
				{
					if(avg.m_fAvg > 0)
					{
						var cell = dgvMap.Rows[iRow].Cells[avg.m_strTable];
						cell.Value = avg.m_fAvg;
						Config.ANALYSIS.RISK Risk = Config.ANALYSIS.GetRisk(avg.m_fAvg);
						switch(Risk)
						{
							case Config.ANALYSIS.RISK.NO:
								cell.Style.BackColor = Theme.Green;
								break;
							case Config.ANALYSIS.RISK.POTENTIAL:
								cell.Style.BackColor = Theme.Yellow;
								break;
							case Config.ANALYSIS.RISK.HIGH:
								cell.Style.BackColor = Theme.Red;
								break;
						}
					}
				}
			}
		}

		private void DgvMap_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
		{
			DataGridView view = sender as DataGridView;

			
			if (e.RowIndex == -1 && e.ColumnIndex >= 0)
			{
				Brush brush = new SolidBrush(this.dgvMap.ForeColor);

				e.PaintBackground(e.ClipBounds, true);
				Rectangle rect = view.GetColumnDisplayRectangle(e.ColumnIndex, true);
				Size titleSize = TextRenderer.MeasureText(e.Value.ToString(), e.CellStyle.Font);
				if (view.ColumnHeadersHeight < titleSize.Width)
					view.ColumnHeadersHeight = titleSize.Width;
				e.Graphics.TranslateTransform(0, titleSize.Width);
				e.Graphics.RotateTransform(-90.0F);
				e.Graphics.DrawString(e.Value.ToString(), this.Font, brush, 
					new PointF(rect.Y - (view.ColumnHeadersHeight - titleSize.Width), rect.X+(e.CellBounds.Width-titleSize.Height)/2));
				e.Graphics.RotateTransform(90.0F);
				e.Graphics.TranslateTransform(0, -titleSize.Width);
				e.Handled = true;
			}
		}
	}
}
