using Newtonsoft.Json;
using PCUT.Entities;
using PCUT.Helpers;
using PCUT.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.Storage;
using Windows.UI.Popups;
using Http.Core;
using Http.Core.Extensions;
using static Http.Core.Constants.HttpConstants;
using Microsoft.IdentityModel.Tokens;
using PCUT.Models.Users;
using Http.Core.Exceptions;

namespace PCUT.ViewModels
{
    public class ChangePasswordViewModel : NotificationBase
    {

        public ICommand ChangePasswordCommand { get; private set; }
        public event PropertyChangedEventHandler PropertyChanged;
        public ObservableCollection<PasswordChange> PasswordChanges { get; private set; }
        private ObservableCollection<UsersModel> _users;
        public ObservableCollection<UsersModel> Users
        {
            get { return _users; }
            set
            {
                if (_users != value)
                {
                    _users = value;
                    OnPropertyChanged(nameof(Users));
                }
            }
        }
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _userId;
        public string UserId
        {
            get { return _userId; }
            set { SetProperty(ref _userId, value); }
        }
        private string _password;
        public string Password
        {
            get { return _password; }
            set
            {
                SetProperty(ref _password, value);
            }
        }
        private string _confirmpassword;
        public string ConfirmPassword
        {
            get { return _confirmpassword; }
            set
            {
                SetProperty(ref _confirmpassword, value);
            }
        }

        public ChangePasswordViewModel()
        {
            ChangePasswordCommand = new RelayCommand(async () => await ChangePassword());
            PasswordChanges = new ObservableCollection<PasswordChange>();
        }

        public async Task ChangePassword()
        {
            if (Password != ConfirmPassword)
            {
                var errorDialog = new MessageDialog("Confirm Password is incorrect!");
                await errorDialog.ShowAsync();
                return;
            }

            if (string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(ConfirmPassword))
            {
                var errorDialog = new MessageDialog("Password and Confirm Password cannot be empty!");
                await errorDialog.ShowAsync();
                return;
            }
            else
            {
                try
                {
                    var passwordChange = new PasswordChange
                    {
                        Password = this.Password,
                    };
                    await ChangePasswordAsync(UserId, passwordChange);
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                    var failDialog = new MessageDialog(ex.Message.ToString());
                    await failDialog.ShowAsync();
                }
            }
        }

        public async Task ChangeDefaultPassword()
        {
                try
                {
                    var passwordChange = new PasswordChange
                    {
                        Password = "123456",
                    };
                    await ChangePasswordAsync(UserId, passwordChange);
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                    var failDialog = new MessageDialog(ex.Message.ToString());
                    await failDialog.ShowAsync();
                }
        }

        private async Task ChangePasswordAsync(string userId, PasswordChange password)
        {
            using (var httpClient = HttpClientFactory.CreateClient(ClientNames.ApiClient))
            {
                try
                {
                    var response = await httpClient.PutAsJsonAsync(Api.UserById.FormatRoute(userId), password);
                    if (response.IsSuccessStatusCode)
                    {
                        var successDialog = new MessageDialog("Password changed successfully!");
                        await successDialog.ShowAsync();
                    }
                    else
                    {
                        var failDialog = new MessageDialog("Failed to change password!");
                        await failDialog.ShowAsync();
                    }
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                    var errorDialog = new MessageDialog($"error: {ex.Message}");
                    await errorDialog.ShowAsync();
                }
            }
        }

    }
}
