using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK.Context.Exception;
using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
using static System.Text.Json.JsonElement;

namespace TEAMModelOS.Controllers.Syllabus
{
    [Route("api/[controller]")]
    [ApiController]
    // [Authorize]
    public class CommonController : BaseController
    {
        public readonly IWebHostEnvironment webHostEnvironment;

        public CommonController(IWebHostEnvironment _webHostEnvironment)
        {
            webHostEnvironment = _webHostEnvironment;

        }
        /// <summary>
        ///获取默认学科及默认年级等数据 bool =true 獲取全部 false 則從request.lang 篩選指定語言的，默認zh-CN
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("DataDefault")]
        public async Task<BaseJosnRPCResponse> DataDefault(JosnRPCRequest<bool> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            string contentRootPath = webHostEnvironment.ContentRootPath;
            JsonDocument document = await GetJson(contentRootPath, "/JsonFile/Core/BaseDataDefault.json");
            if (!request.@params)
            {
                List<JsonElement> jsonElements = new List<JsonElement>();
                foreach (JsonElement element in document.RootElement.EnumerateArray())
                {
                    if (element.TryGetProperty("lang", out JsonElement json))
                    {
                        if (json.GetString().Equals(request.lang))
                        {
                            jsonElements.Add(element);
                        }
                    }
                }
                return builder.Data(jsonElements).build();
            }
            else
            {
                return builder.Data(document.RootElement).build();
            }
        } 

        public static async Task<JsonDocument> GetJson(string contentRootPath, string name)
        {
            try
            {
                string path = contentRootPath + name;
                var fs = await System.IO.File.ReadAllTextAsync(path, Encoding.UTF8);
                return JsonDocument.Parse(fs);
            }
            catch (Exception e)
            {
                new BizException(e.Message);
            }
            return null;
        }
    }
}
