using System;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TEAMModelOS.SDK;
using Microsoft.Extensions.Configuration;
using System.Text.Json;

namespace TEAMModelOS.Controllers.IoT
{
    /// <summary>
    /// 目前IoT儀表運營使用。
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class IoTController : ControllerBase
    {
        private readonly IConfiguration _config;
        private readonly IHttpClientFactory _httpClientFactory;

        public IoTController(IConfiguration configuration, IHttpClientFactory httpClientFactory)
        {
            _config = configuration;
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 資料表Data
        /// </summary>
        /// <param name="schoolShortCode"></param>
        /// <returns></returns>
        [HttpGet("GetTestIoTData")]
        public async Task<BaseResponse> GetTestIoTData(string schoolShortCode)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient();
                var url = _config.GetValue<string>("CoreAPIUrl");

                var response = await httpClient.GetAsync($"https://{url}/values/schooldashboard/{schoolShortCode}");

                response.EnsureSuccessStatusCode();
                string content = await response.Content.ReadAsStringAsync();
                ResponseBuilder builder = ResponseBuilder.custom();
                return builder.Data(JsonDocument.Parse(content).RootElement).build();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }
    }
}
