/*-------------------------------------------------------------------------
 * 功能描述：UploadService
 * 作者：xulisong
 * 创建时间： 2019/7/30 10:44:23
 * 版本号：v1.0
 *  -------------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using MBIRevitBase.Config;
using MBIRevitBase.Tools;
using Polly;
using Polly.Retry;
using SAGA.DotNetUtils.Logger;

namespace MBIRevitBase.Services
{
    /// <summary>
    /// 上传服务类
    /// </summary>
    public class UploadService
    {
        public static BResult UploadExportFile(string result)
        {
            BResult tt = null;
            try
            {
                tt= UploadExportFileRetry<BResult>(result);
            }
            catch (Exception e)
            {
                tt=new BResult(false,e.Message);
            }
            //var tt= DelayRetryPolicy(result);
            return tt;
        }
        /// <summary>
        /// 上传导出文件
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static T UploadExportFileRetry<T>(string result)where T:BResult
        {
            var stream = ZipUtils.ZipString(result, "export.json");
            var url = ApiConfig.AlgorithmUrl();
            var tt = HttpUtils.PostFormDataFileThrowException(url, stream) as T;
            return tt;
        }

        static BResult DelayRetryPolicy(string result)
        {
            try
            {
#if DEBUG
                var waitAndRetryPolicy = Policy.Handle<Exception>().WaitAndRetry(4,
                    (i, t) => TimeSpan.FromSeconds(5), ReportError);
#else
                var waitAndRetryPolicy = Policy.Handle<Exception>().WaitAndRetry(4,
                    (i, t) => TimeSpan.FromSeconds(1*60), ReportError);
#endif
                return waitAndRetryPolicy.Execute<BResult>(()=> UploadExportFileRetry<BResult>(result));
            }
            catch (Exception e)
            {
                Log4Net.Debug($"Execute failed,Message:{e.Message}");
                return "文件上传失败！"+e.Message;
            }
        }
        static void ReportError(Exception e, TimeSpan timeSpan, int intento, Context context)
        {
            Log4Net.Debug($"异常{intento:00} <调用秒数：{timeSpan.Seconds} 秒>\t 执行时间：{DateTime.Now}");
        }
    }
}
