using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using 电子展板.Base;
using 电子展板.Utility;
using 电子展板.Utility.Core;
using 电子展板.Utility.Extension;
using 电子展板.Utility.Logs;
using 电子展板.Utility.Other;
using 电子展板.Utility.Web;

namespace 电子展板.Controller
{
    public class IndexController : BaseController
    {
        /// <summary>
        /// 后台首页视图。
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("")]
        public ActionResult Index()
        {
            return Resouce("/Views/Index.html", "text/html");
        }

        [HttpGet, Route("getConfig")]
        public ActionResult GetConfig()
        {
            return Json(GlobalVariable.Config);
        }


        /// <summary>
        /// 上传头像。
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("uploadImage")]
        public ActionResult UploadImage()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string path = MyEnvironment.Root("/Upload");
            var provider = new WithExtensionMultipartFormDataStreamProvider(path, UUID.StrSnowId);
            var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
            if (fileData.FileData.Count == 0)
            {
                return Error();
            }
            var file = fileData.FileData[0];
            string virtualPath = "/Upload/" + Path.GetFileName(file.LocalFileName);
            return Success("上传成功", virtualPath);
        }


        [HttpGet, Route("Upload/{id}")]
        public ActionResult GetUploadFile([FromUri] string id)
        {
            string filePath = MyEnvironment.Root($"/Upload/{id}");
            string contentType = System.Web.MimeMapping.GetMimeMapping(filePath);
            return PhysicalFile(filePath, contentType, id);
        }


        [HttpPost, Route("save")]
        public ActionResult Save([FromBody] MyConfig config)
        {
            LogHelper.Instance.Info($"用户保存了配置:{JsonHelper.ToJson(config)}");
            //保存
            PropertyInfo[] propertyInfos = typeof(MyConfig).GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                object value = propertyInfo.GetValue(config);
                propertyInfo.SetValue(GlobalVariable.Config, value);
            }
            GlobalVariable.SaveConfig();
            EventBus.Instance.Publish("save", "");
            return Success();
        }



    }
}
