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

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamarinMSSQL.Models;

namespace XamarinMSSQL.Views
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class SqlPage : ContentPage
	{
		private List<EmployeeItem> employeeItems;

		public SqlPage()
		{
			InitializeComponent();
			InitInstance();
		}

		private void InitInstance()
		{
			GetDataFromSQLServer();

			mainListView.EndRefresh();
		}

		private void GetDataFromSQLServer()
		{
			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
			{
				DataSource = "peacecloud.synology.me,21433",
				InitialCatalog = "Study",
				UserID = "study",
				Password = "Study123$",
				IntegratedSecurity = false
			};

			SqlConnection conn = new SqlConnection(builder.ConnectionString);
			try
			{
				conn.Open();
				SqlDataAdapter adapter = new SqlDataAdapter();
				string qry = "SELECT * FROM EMPLOYEE";
				adapter.SelectCommand = new SqlCommand(qry, conn);
				DataSet ds = new DataSet();
				adapter.Fill(ds);

				employeeItems = new List<EmployeeItem>();
				foreach (DataRow row in ds.Tables[0].Rows)
				{
					employeeItems.Add(new EmployeeItem()
					{
						ID = (int)row["ENO"],
						Name = (string)row["ENAME"],
						Job = (string)row["JOB"],
						HireDate = (DateTime)row["HIREDATE"],
						Salary = (int)row["SALARY"],
						Commission = (int)(row["COMMISSION"] == DBNull.Value || row["COMMISSION"] == null ? 0 : row["COMMISSION"])
					});
				}

				mainListView.ItemsSource = employeeItems;
			}
			catch (Exception ex)
			{
				DisplayAlert("Error", ex.Message, "OK");
				throw;
			}
		}

		private void mainListView_Refreshing(object sender, EventArgs e)
		{
			GetDataFromSQLServer();

			mainListView.EndRefresh();
		}

		private void mainListView_ItemTapped(object sender, ItemTappedEventArgs e)
		{
			EmployeeItem employeeItem = (EmployeeItem)e.Item;
			Navigation.PushAsync(new EmployeeDetailPage(employeeItem));
		}
	}
}