using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Data;
namespace WpfApplication19
{
	/// <summary>
	/// Interaction logic for DailyCheck.xaml
	/// </summary>
	public partial class DailyCheck : Window
	{
		ObservableCollection<DailyChecker> _dailyChecks = new ObservableCollection<DailyChecker>();
		DataGridCellInfo _cell;
		DataGridColumn _col;
		DailyChecker _item;
		SqlConnection _proConn;
		DateTime _now, _tomorrow;
		string _shift;
		public DailyCheck()
		{
			InitializeComponent();

			//nowLabel.Content = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
			//var test = DateTime.Now + 1;
			_now  = DateTime.Now.Date;
			_tomorrow = _now.AddDays(1);
			var c = DateTime.Now.AddDays(1);

			var hr = DateTime.Now.TimeOfDay.Hours;
			//shiftCB.SelectionChanged -= shiftCB_SelectionChanged;
			if(hr >= 8 && hr <= 19){
				_shift = "day";
				shiftCB.SelectedIndex = 0;
			}else{
				_shift = "night";
				shiftCB.SelectedIndex = 1;
			}
			

			datePicker.SelectedDateChanged -= datePicker_SelectedDateChanged;
			datePicker.SelectedDate  =_now;
			datePicker.SelectedDateChanged += datePicker_SelectedDateChanged;

			shiftCB.SelectionChanged += shiftCB_SelectionChanged;
			try
			{
				_proConn = Utils.createSqlConnection("productionDbCS");
			
			}
			catch (SqlException se)
			{
				MessageBox.Show("productionDbCS : ", se.Message);
			}
			//var w = (MainWindow)Application.Current.MainWindow;
			//_proConn = w.proConn;
			initDataGrid();
			//dailyCheckGrid.Focus();


		}
		void initDataGrid(){
			setGrid(_now, _tomorrow, _shift);
			
		
		}

		private void setGrid(DateTime from, DateTime to, string shift)
		{
			var id = Utils.getSetting("currentMachine");
			var sql = string.Format("select * from daily_checks where created_at >= '{0:yyyy-MM-dd}' and created_at < '{1:yyyy-MM-dd}' and machine_id = {2} and shift = '{3}'"
			, from,to, id, shift);
			var reader = Utils.Query(_proConn, sql);

			dailyCheckGrid.ItemsSource = null;
			_dailyChecks.Clear();
			if (reader.HasRows)
			{
				while (reader.Read())
				{

					_dailyChecks.Add(new DailyChecker()
					{
						header = reader["header"].ToString().ToUpper(),
						p1 = Math.Round(Convert.ToDouble(reader["p1"]), 2),
						p2 = Math.Round(Convert.ToDouble(reader["p2"]), 2),
						p3 = Math.Round(Convert.ToDouble(reader["p3"]), 2),
						avg = Math.Round(Convert.ToDouble(reader["avg"]), 2),
						result = reader["result"].ToString()
					});
				}

			}
			else
			{
				_dailyChecks.Add(new DailyChecker() { header = "OB", p1 = 0, p2 = 0, p3 = 0, avg = 0 });
				_dailyChecks.Add(new DailyChecker() { header = "OC", p1 = 0, p2 = 0, p3 = 0, avg = 0 });
				_dailyChecks.Add(new DailyChecker() { header = "RH", p1 = 0, p2 = 0, p3 = 0, avg = 0 });
			}
			reader.Close();
			dailyCheckGrid.Items.Clear();
			dailyCheckGrid.ItemsSource = _dailyChecks;
		}

	
		private void saveBtn_Click(object sender, RoutedEventArgs e)
		{
			int row, col;
			string header;
			//dailyCheckGrid.Focus();
			try{
				header = _cell.Column.Header.ToString();
				row  = _dailyChecks.IndexOf((_cell.Item as DailyChecker));
				col = _col.DisplayIndex;
			}catch{
				dailyCheckGrid.Focus();
				dailyCheckGrid.CurrentCell = new DataGridCellInfo(
							dailyCheckGrid.Items[0], dailyCheckGrid.Columns[1]);
				dailyCheckGrid.BeginEdit();
				header = "P1";
				row = 0;
				col = 1;
				_item = _dailyChecks[0];
			}
			switch(header){
				case "P1":
					//var c = dailyCheckGrid.CurrentItem as DailyChecker;
					_item.p1 = Convert.ToDouble(measureBlock.Text);
				break;
				case "P2":
					_item.p2 = Convert.ToDouble(measureBlock.Text);
				break;
				case "P3":
					_item.p3 = Convert.ToDouble(measureBlock.Text);
				break;
				
			}
			_item.avg = Math.Round((_item.p1 + _item.p2 + _item.p3)/3, 2);
			if(_item.header == "OB"){
				if(_item.avg >= 0.59 && _item.avg <= 0.70){
					_item.result = "OK";
				}else {
					_item.result = "NG";
				}
			}
			if(_item.header == "OC"){
				if (_item.avg >= 0.28 && _item.avg <= 0.37)
				{
					_item.result = "OK";
				}
				else
				{
					_item.result = "NG";
				}
			}
			dailyCheckGrid.Items.Refresh();
			dailyCheckGrid.Focus();
			if(header != "Header" && header != "Avg" && header != "P3"){
				dailyCheckGrid.CurrentCell = new DataGridCellInfo(
						dailyCheckGrid.Items[row], dailyCheckGrid.Columns[col + 1]);
				dailyCheckGrid.BeginEdit();
			}
			if(header == "P3"){
				try{
				dailyCheckGrid.CurrentCell = new DataGridCellInfo(
						dailyCheckGrid.Items[row+1], dailyCheckGrid.Columns[1]);
				dailyCheckGrid.SelectedItem = dailyCheckGrid.Items[row + 1];
				dailyCheckGrid.BeginEdit();
				}catch{
					dailyCheckGrid.CurrentCell = new DataGridCellInfo(
							dailyCheckGrid.Items[0], dailyCheckGrid.Columns[1]);
					dailyCheckGrid.SelectedItem = dailyCheckGrid.Items[0];
					dailyCheckGrid.BeginEdit();
				}
			}
			
		}

	
	
		
		
		private void dailyCheckGrid_GotFocus(object sender, RoutedEventArgs e)
		{
			_cell = dailyCheckGrid.CurrentCell;
			_col = dailyCheckGrid.CurrentColumn;
			_item = dailyCheckGrid.CurrentItem as DailyChecker;
			
		}

		

		private void dailyCheckGrid_Loaded(object sender, RoutedEventArgs e)
		{
			dailyCheckGrid.Focus();
			dailyCheckGrid.CurrentCell = new DataGridCellInfo(
										dailyCheckGrid.Items[0], dailyCheckGrid.Columns[1]);
			dailyCheckGrid.BeginEdit();
		}

		private void commitBtn_Click(object sender, RoutedEventArgs e)
		{
			commitData();
			MessageBox.Show("Commit Daily Check Complete");
			Close();
		}

		private void commitData()
		{
			var id = Utils.getSetting("currentMachine");
			var sql = string.Format("delete daily_checks where machine_id = {0} and created_at >= '{1:yyyy-MM-dd}' and created_at < '{2:yyyy-MM-dd}' and shift = '{3}'", id, _now, _tomorrow, _shift);
			var reader = Utils.Query(_proConn, sql);
			reader.Close();
			string empid = GlobalVars.user.empid;
			foreach (var item in _dailyChecks)
			{

				sql = string.Format("insert into daily_checks(header, p1, p2, p3, avg, created_at, updated_at,machine_id, empid, shift, result) values('{0}', {1}, {2}, {3}, {4}, '{5}', '{6}', {7}, '{8}', '{9}', '{10}')"
					, item.header.ToUpper(), item.p1, item.p2, item.p3, item.avg, _now, DateTime.Now, id, empid, _shift, item.result);
				reader = Utils.Query(_proConn, sql);
				reader.Close();
			}
		}

		private void datePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
		{
			//MessageBox.Show("change date");
			if (commitBtn.IsEnabled == true)
				commitData();
			var d =  (DateTime)datePicker.SelectedDate;
			var shift = (shiftCB.SelectedItem as ComboBoxItem).Tag.ToString();
			if (d.Date == DateTime.Now.Date && shift == _shift)
			{
				saveBtn.IsEnabled = true;
				commitBtn.IsEnabled = true;
			}
			else
			{
				saveBtn.IsEnabled = false;
				commitBtn.IsEnabled = false;
			}
			var from  = (DateTime)datePicker.SelectedDate;
			
			setGrid(from.Date, from.Date.AddDays(1), shift);
		}

		private void shiftCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			//var d = (DateTime)datePicker.SelectedDate;
			if( commitBtn.IsEnabled == true)
				commitData();
			var d = (DateTime)datePicker.SelectedDate;
			var shift = (shiftCB.SelectedItem as ComboBoxItem).Tag.ToString();
			if (d.Date == DateTime.Now.Date && shift == _shift)
			{
				saveBtn.IsEnabled = true;
				commitBtn.IsEnabled = true;
			}
			else
			{
				saveBtn.IsEnabled = false;
				commitBtn.IsEnabled = false;
			}
			var from = (DateTime)datePicker.SelectedDate;

			setGrid(from.Date, from.Date.AddDays(1), shift);
		}

		private void Window_Closed(object sender, EventArgs e)
		{
			if (commitBtn.IsEnabled == true)
				commitData();
		}

		

		

		
		
		
	}
}
