using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
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 MonsterPage : ContentPage
	{
		private List<Monster> monsters;

		public MonsterPage()
		{
			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 MONSTER";
				adapter.SelectCommand = new SqlCommand(qry, conn);
				DataSet ds = new DataSet();
				adapter.Fill(ds);

				monsters = new List<Monster>();
				foreach (DataRow row in ds.Tables[0].Rows)
				{
					monsters.Add(new Monster()
					{
						Id = (int)row["id"],
						Name = (string)row["name"],
						Portrait = ConvertObject<string>(row["portrait"], "https://cdn3.iconfinder.com/data/icons/fantasy-and-role-play-game-adventure-quest/512/Spell_Book-256.png"),
						HP = (int)row["hp"],
						MP = (int)row["mp"],
						Attack = (double)row["attack"],
						Defence = (double)row["defence"],
						Description = ConvertObject<string>(row["description"], ""),
					});
				}

				mainListView.ItemsSource = monsters;
			}
			catch (Exception ex)
			{
				return;
			}
		}

		private T ConvertObject<T>(object obj, T defaultValue)
		{
			if (obj == null || obj == DBNull.Value)
				return defaultValue;

			return (T)obj;
		}

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

			mainListView.EndRefresh();
		}

		private void mainListView_ItemTapped(object sender, ItemTappedEventArgs e)
		{
			Monster monster = (Monster)e.Item;
			Navigation.PushAsync(new MonsterDetailPage(monster));
		}
	}
}