using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Vpn.Request.Product;
using Hncore.Pass.Vpn.Response.Product;
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Hncore.Pass.Vpn.Controllers
{
    [ApiVersion("1.0")]
    [Route("api/course/v{version:apiVersion}/agent/[action]")]
    public class AgentController : HncoreControllerBase
    {
        private AgentService m_AgentService;
        IConfiguration m_Configuration;
        public AgentController(AgentService _AgentService,IConfiguration configuration)
        {
            m_AgentService = _AgentService;
            m_Configuration = configuration;
        }        
        [HttpPost]
        public async Task<ApiResult> Login([FromBody] AgentLoginRequest request)
        {
           return await m_AgentService.Login(request);         
        }
        [HttpGet]
        public async Task<ApiResult> GetCode([FromQuery] int productId)
        {
            var ret = await m_AgentService.GetCode(productId);
            if (ret.Item1 != null)
            {
                var file = $"codes/{Guid.NewGuid().ToString("N")}.jpg";
                var wwwrootFile = $"wwwroot/{file}";
                using (FileStream fs = new FileStream(wwwrootFile, FileMode.Create))
                {
                    await fs.WriteAsync(ret.Item1, 0, ret.Item1.Length);
                }
                return Success(new CodeResponse()
                {
                    Key = ret.Item2,
                    CodeImage = $"{m_Configuration["Service_BaseUrl"]}{file}"
                });
            }
            return Success(new CodeResponse()
            {
                Key = "",
                CodeImage = ""
            });
        }
    }
}
