using System;
using System.Collections.Generic;

using Xamarin.Forms;

using InABox.Core;
using InABox.Configuration;
using InABox.Clients;

namespace InABox.Mobile
{

    class SettingsBinding : ConnectionSettings
    {
        public String DeviceID { get; set; }
        public String AppVersion { get; set; }

        public void Load(ConnectionSettings settings)
        {
            URL = settings.URL;
            Port = settings.Port;
            UserID = settings.UserID;
            Password = settings.Password;
            AutoUpdateLocation = settings.AutoUpdateLocation;
        }

        public void Unload(ConnectionSettings settings)
        {
            settings.URL = URL;
            settings.Port = Port;
            settings.UserID = UserID;
            settings.Password = Password;
            settings.AutoUpdateLocation = AutoUpdateLocation;
        }

    }

    public partial class Settings : ContentPage
    {

        SettingsBinding binding = new SettingsBinding();
        ConnectionSettings settings = null;

        public Settings(ConnectionSettings Settings, bool Modal = false)
        {
            InitializeComponent();
            settings = Settings;

            binding.Load(settings);
            binding.DeviceID = MobileUtils.GetDeviceID();
            IAppVersion appversion = DependencyService.Get<IAppVersion>();
            binding.AppVersion = appversion.GetVersion();

            this.BindingContext = binding;

            if ((SaveButton != null) && Modal)
            {
                CancelButton.IsVisible = true;
                SaveButton.IsVisible = true;
                SettingsGrid.Margin = new Thickness(10, 25, 10, 10);
            }
            else
            {
                SettingsGrid.Margin = new Thickness(10, 10, 10, 10);
                NavigationPage.SetBackButtonTitle(this, "Cancel");

                ToolbarItems.Clear();

                ToolbarItems.Add(new ToolbarItem("Save", "", () =>
                {
                    binding.Unload(settings);
                    new LocalConfiguration<ConnectionSettings>().Save(settings);
                    ClientFactory.SetClientType(typeof(RemoteClient<>), settings.URL, settings.Port);
                    ClientFactory.ValidateUser(settings.UserID, settings.Password);
                    Navigation.PopAsync();
                }));
            }
            Title = "Settings";
        }

        void CancelClicked(object sender, System.EventArgs e)
        {
            Navigation.PopModalAsync();
        }

        void SaveClicked(object sender, System.EventArgs e)
        {
            binding.Unload(settings);
            new LocalConfiguration<ConnectionSettings>().Save(settings);
            ClientFactory.SetClientType(typeof(RemoteClient<>), settings.URL, settings.Port);
            ClientFactory.ValidateUser(settings.UserID, settings.Password);
            Navigation.PopModalAsync();
        }
    }
}
