using BlazorBootstrap;
using HushianWebApp.Services;
using Microsoft.AspNetCore.Components;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using static System.Net.WebRequestMethods;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace HushianWebApp.Service
{
    public class BaseController
    {
        private readonly HttpClient _Http;
        private readonly NavigationManager _NavigationManager;
        private readonly ToastService _ToastService;
        public BaseController(HttpClient http, NavigationManager navigationManager, ToastService toastService)
        {
            _Http = http;
            _NavigationManager = navigationManager;
            _ToastService = toastService;
        }

        public async Task<bool> IsOnline()
        {
            var result = await _Http.GetAsync("v1/Auth/IsOnline");
            return result.IsSuccessStatusCode;
        }
        public async Task SetToken(string token)
        {
            _Http.DefaultRequestHeaders.Add("Authorization",
                $"Bearer {token}");
        }
        public async Task RemoveToken()
        {
            if (_Http.DefaultRequestHeaders.Any(t => t.Key == "Authorization"))
                _Http.DefaultRequestHeaders.Remove("Authorization");
        }
        public async Task<HttpResponseMessage> Get(string route,string From="")
        {
            var result = await _Http.GetAsync(route);
            return await Check(result);

        }
        public async Task<HttpResponseMessage> Delete(string route)
        {
            var result = await _Http.DeleteAsync(route);
            return await Check(result);
        }
        public async Task<HttpResponseMessage> Post(string route, object mode)
        {
            var result = await _Http.PostAsJsonAsync(route, mode);
            return await Check(result);

        }
        public async Task<Tuple<string, HttpResponseMessage>> PostLogin(string route, object mode)
        {
      
            var result = await _Http.PostAsJsonAsync(route, mode);
            if (result.IsSuccessStatusCode)
            {
                return Tuple.Create( "ok",result);
            }
            else if (result.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                try
                {
                    var Errors = await result.Content.ReadFromJsonAsync<List<string>>();
                    if (Errors.Count > 0)
                    {
                        _ToastService.Notify(new ToastMessage(ToastType.Danger, Errors[0]));
                    }
                    else _ToastService.Notify(new ToastMessage(ToastType.Danger, "خطا در اجرای عملیات"));

                    return Tuple.Create(Errors[0], result);

                }
                catch (Exception)
                {
                    _ToastService.Notify(new ToastMessage(ToastType.Danger, "خطا در اجرای عملیات"));
                    return Tuple.Create("error", result);
                }
            }
            else if (!result.IsSuccessStatusCode)
            {

                _NavigationManager.NavigateTo("Unhandled");
                return Tuple.Create("Unhandled", result);
            }
            return Tuple.Create("no", result);

        }
        public async Task<HttpResponseMessage> Post(string route,bool redirectToLogin=true)
        {
            var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
            var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var result = await _Http.PostAsync(route, httpContent);

            return await Check(result, redirectToLogin);
        }
        public async Task<HttpResponseMessage> Put(string route, object mode)
        {
            var result = await _Http.PutAsJsonAsync(route, mode);
            return await Check(result);
        }
        public async Task<HttpResponseMessage> Put(string route)
        {
            var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
            var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var result = await _Http.PutAsync(route, httpContent);
            return await Check(result);
        }
        private async Task<HttpResponseMessage> Check(HttpResponseMessage result, bool redirectToLogin = true)
        {
            if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized && redirectToLogin)
                _NavigationManager.NavigateTo("Login");
            else if (result.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                try
                {
                    var Errors = await result.Content.ReadFromJsonAsync<List<string>>();
                    if (Errors.Count > 0)
                    {
                        if (Errors[0] == "PhoneNumberNotConfirmed")
                        {
                            _ToastService.Notify(new ToastMessage(ToastType.Danger, "این کاربری احراز نشده اگر مالک آن هستید احراز کنید"));

                        }
                        else
                        {

                            _ToastService.Notify(new ToastMessage(ToastType.Danger, Errors[0].Split(':').Length==2 ? Errors[0].Split(':')[1] : Errors[0])); 
                        }
                    }
                    else _ToastService.Notify(new ToastMessage(ToastType.Danger, "خطا در اجرای عملیات"));

                }
                catch (Exception)
                {
                    _ToastService.Notify(new ToastMessage(ToastType.Danger, "خطا در اجرای عملیات"));
                }
            }
            else if (result.StatusCode == System.Net.HttpStatusCode.Forbidden)
                _ToastService.Notify(new ToastMessage(ToastType.Danger, "به این بخش دسترسی ندارید"));
            //else if (result.StatusCode == System.Net.HttpStatusCode.NotFound)
            //{
            //    string From ="" ;

            //    if (result.RequestMessage.RequestUri.AbsolutePath.ToString().Contains("GetCompany"))  From = "شرکت";
                
            //_ToastService.Notify(new ToastMessage(ToastType.Danger, $"{From} یافت نشد"));

            //}
            else if (!result.IsSuccessStatusCode && (result.StatusCode != System.Net.HttpStatusCode.NotFound))
            {

                _NavigationManager.NavigateTo("Unhandled");
            }

            return result;

        }
    }
}
