using DynamicExpresso;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using wispro.sp.entity;
using wispro.sp.share;
using wispro.sp.web.Auth;
using wispro.sp.web.Models;

namespace wispro.sp.web.Services
{
    public class AppealTypeService
    {
        private readonly HttpClient _httpClient;
        private readonly JwtAuthenticationStateProvider _jwt;
        private  List<AppealType> AppealTypes;

        public AppealTypeService(HttpClient httpClient, AuthenticationStateProvider jwt)
        {
            _httpClient = httpClient;
            _jwt = (JwtAuthenticationStateProvider)jwt;

            
        }

        public async Task<AppealRecord> getAppealRecord(int appealRecordId)
        {
            var data = await _httpClient.GetFromJsonAsync<AppealRecord>($"http://localhost:39476/api/Appeal/GetAppealRecord?Id={appealRecordId}");
            return data;
        }

        public async Task<List<InputFieldValue>> GetInputFieldValues(int id, int state)
        {
            var data = await _httpClient.GetFromJsonAsync<List<InputFieldValue>>($"http://localhost:39476/api/Appeal/GetInputFieldValues?Id={id}&state={state}");
            return data;
        }

        public async Task<List<AppealType>> GetItems()
        {
            if (AppealTypes == null)
            {
                AppealTypes = await _httpClient.GetFromJsonAsync<List<AppealType>>($"http://localhost:39476/api/Appeal/GetAppealTypes");
                
            }
            return AppealTypes;
        }

        public List<AppealType> GetItems(PerformanceItem item)
        {
            List<AppealType> retList = new List<AppealType>();

            foreach (var at in AppealTypes)
            {
                if (!string.IsNullOrWhiteSpace(at.CanDoExpress))
                {
                    var interpreter = new Interpreter();
                    //Console.WriteLine(at.CanDoExpress);
                    Func<PerformanceItem, bool> func = interpreter.ParseAsDelegate<Func<PerformanceItem, bool>>(at.CanDoExpress, "p");
                    bool result = func.Invoke(item);
                    
                    if (result)
                    {
                        retList.Add(at);
                    }
                }
                else
                {
                    retList.Add(at);
                }
            }

            return retList;
        }

        public async Task<List<AppealRecord>> GetUserAppeals(int? userid)
        {
            var data = await _httpClient.GetFromJsonAsync<List<AppealRecord>>($"http://localhost:39476/api/Appeal/GetAppealRecords?userId={userid}");
            return data;
        }

        public async Task<AppealType> GetItem(int appealTypeId)
        {
            if (AppealTypes == null)
            {
                AppealTypes = await _httpClient.GetFromJsonAsync<List<AppealType>>($"http://localhost:39476/api/Appeal/GetAppealTypes");
            }

            var retData = AppealTypes.Where<AppealType>(ap => ap.Id == appealTypeId).FirstOrDefault();

            return retData;
        }

        public async Task<List<InputField>> GetInputFields(int appealTypeId,int State)
        {
            Console.WriteLine($"begin GetInputFields: appealTypeId={appealTypeId};State={State}");
            var data = await _httpClient.GetFromJsonAsync<List<InputField>>($"http://localhost:39476/api/Appeal/GetInputField?appealTypeId={appealTypeId}&state={State}");
            return data;
        }

        public async Task<List<AttachFile>> GetAppealRecordAttachFiles(int appealRecordId)
        {
            var data = await _httpClient.GetFromJsonAsync<List<AttachFile>>($"http://localhost:39476/api/Appeal/GetAppealRecordAttachFiles?appealRecordId={appealRecordId}");
            return data;
        }

        public async Task CreateAppeal(CreateAppealModel model)
        {
            List<AttachFile> attachFiles = new List<AttachFile>();

            foreach (var file in model.FileList)
            {
                AttachFile atfile = new AttachFile();
                var result = file.GetResponse<List<AttachFile>>();
                atfile.Id = result[0].Id;
                attachFiles.Add(atfile);
            }

            string strUrl = $"http://localhost:39476/api/Appeal/CreateAppeal?ItemId={model.Item.Id}&typeid={model.AppealType.Id}&reviewerId={model.AppealRecord.ReviewerId}";
            AppealObject appealObject = new AppealObject();
            appealObject.attachFiles = attachFiles;
            appealObject.inputFieldValues = model.inputFieldValues;
            foreach(var fValue in appealObject.inputFieldValues)
            {
                fValue.InputField = null;
            }

            var data = await _httpClient.PostAsJsonAsync<AppealObject>(strUrl, appealObject);

            Console.WriteLine(JsonSerializer.Serialize(data));
        }

        public async Task ReviewerAppeal(ReviewerAppealModel model)
        {

            string strUrl = $"http://localhost:39476/api/Appeal/ReviewerAppeal?appealRecordId={model.AppealRecord.Id}";
            AppealObject appealObject = new AppealObject();
            appealObject.inputFieldValues = model.inputFieldValues;

            foreach (var fValue in appealObject.inputFieldValues)
            {
                fValue.InputField = null;
            }

            var data = await _httpClient.PostAsJsonAsync<AppealObject>(strUrl, appealObject);

            if (!data.IsSuccessStatusCode)
            {
                string strContent = await data.Content.ReadAsStringAsync();
                throw new Exception(strContent);
            }
        }
        
        
    }
}
