using BITKit;
using IDIS;
using IDIS.Models;
using IDIS.Services;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace IDIS_Server_SIM.Controllers;

[ApiController]
public class IDIS_ServiceController:Controller
{
	private readonly IDIS_Service _service;
	public IDIS_ServiceController(IDIS_Service service)
	{
		_service = service;
	}
	[HttpGet]
	[Route("info")]
	public IActionResult Info()
	{
		return new ContentResult
		{
			Content = Environment.MachineName
		};
	}
	[HttpGet]
	[Route("/identityv2/data/detail")]
	public async Task<IActionResult> Query(string handle)
	{
		try
		{
			var result = await _service.QueryAsync(handle);
			var response = new IDIS_Response(result);
			var json = JsonConvert.SerializeObject(response);
			//return Ok(JsonConvert.SerializeObject(response));
			return new ContentResult()
			{
				Content = json,
				ContentType = "application/json",
				StatusCode = 200
			};
		}
		catch (Exception e)
		{
			return BadRequest(new IDIS_Response(e.Message,false)
			{
				Status = 2
			});
		}
	}

	[HttpGet]
	[Route("isExist")]
	public async Task<IActionResult> IsExist(string code)
	{
		return Ok(new IDIS_Response(await _service.IsExistAsync(code)));
	}
	
	[HttpPost]
	[Route("/identityv2/data")]
	public async Task<IActionResult> Register()
	{
		try
		{
			using var reader = new StreamReader(Request.Body);
			var json = await reader.ReadToEndAsync();
			var data = JsonConvert.DeserializeObject<IDIS_Register_Data>(json)!;
			await _service.RegisterAsync(data.Handle, data.TemplateVersion, data.Value);
			return Ok(new IDIS_Response());
		}
		catch (Exception e)
		{
			return BadRequest(new IDIS_Response(e.Message,false)
			{
				Status = 2
			});
		
		}
	}
	[HttpGet]
	[Route("update")]
	public string Update()
	{
		return "err:0";
	}
	[HttpGet]
	[Route("delete")]
	public async Task<bool> Delete (string code)
	{
		await _service.DeleteAsync(code);
		return true;
	}
}