using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.Repository.Domain;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>
    /// app 文件版本管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SysAppFilesController : ControllerBase
    {
        SysAppFilesApp sysAppFilesApp;

        public SysAppFilesController(SysAppFilesApp sysAppFilesApp)
        {
            this.sysAppFilesApp = sysAppFilesApp;
        }

        #region app文件

        /// <summary>
        /// 添加App文件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public Response<bool> AddAppFiles([FromBody] SysAppFiles model)
        {
            Response<bool> response = new Response<bool>();
            try
            {
                response = sysAppFilesApp.AddAppFiles(model);
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 获取下载更新的文件路径
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public Response<object> GetUpdateFiles(string project)
        {
            Response<object> response = new Response<object>();
            try
            {
                response.Result = sysAppFilesApp.GetUpdateFiles(project);
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 下载app文件
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult DownLoadAppFile(string project)
        {
            var model = sysAppFilesApp.GetByProject(project);
            if (model != null)
            {
                string path = model.filepath;
                var root = AppDomain.CurrentDomain.BaseDirectory;

                if (System.IO.File.Exists(root + path))
                {
                    var readStream = System.IO.File.ReadAllBytes(root + path);
                    return File(readStream, "application/octet-stream", "drone_enforcement.apk");
                }
            }
            return null;
        }

        #endregion
    }
}
