using PlantBox.Client.Extensions;
using PlantBox.Client.Forms.Plant;
using PlantBox.Client.Models;
using PlantBox.Client.Resources;
using PlantBox.Client.Util;
using PlantBox.Client.ViewModels;
using PlantBox.Shared.Communication;
using PlantBox.Shared.Communication.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace PlantBox.Client.Forms
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class HomePage : ContentPage
	{
		public HomePage()
		{
			InitializeComponent();
		}

        private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            var plant = (PlantInfo)e.Item;

            // Prepare view model
            var viewModel = new PlantViewModel(plant);

            await Navigation.PushAsync(new PlantPage(viewModel)
            {
                Title = plant.Name
            });
        }

        protected override bool OnBackButtonPressed()
        {
            App.MasterPage.IsPresented = true;

            return true;
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            string input = await FormsDialog.InputBox(Navigation, Locale.AddPlantBox, Locale.EnterValidID);

            if (ulong.TryParse(input, out ulong id) && await IsValidId(id))
            {
                App.Settings.IDs.Add(id);

                await App.Settings.SaveAsync();
                await Refresh();
            }
            else
            {
                await DisplayAlert(Locale.Error, Locale.InvalidID, Locale.OK);
            }
        }

        private async Task<bool> IsValidId(ulong id)
        {
            string plantName = "";

            try
            {
                using (var client = new TcpClient(App.Settings.BrokerIP, Connection.TCP_CLIENT_PORT))
                using (var commandStream = new CommandStream(client.GetStream()))
                {
                    await commandStream.SendAsync(new InfoRequest().ToCommandPacket(id));

                    (_, var info) = await commandStream.ReceiveAsync<InfoResponse>();

                    plantName = info.Name;
                }
            }
            catch (Exception)
            {

            }

            return plantName != "";
        }

        private async void ListView_Refreshing(object sender, EventArgs e)
        {
            await Refresh();

            List.EndRefresh();
        }

        private async Task Refresh()
        {
            var homeViewModel = (HomeViewModel)BindingContext;

            await Task.Run(() => homeViewModel.Plants = homeViewModel.LoadPlants(App.Settings.IDs));
        }
    }
}