/*-------------------------------------------------------------------------
 * 功能描述：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;

namespace MBIRevitBase.Services
{
    /// <summary>
    /// 上传服务类
    /// </summary>
    public class UploadService
    {
        public static BResult UploadExportFile(string result)
        {
            return DelayRetryPolicy(result);
        }
        /// <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();
            Console.WriteLine("BeginUploadData");
            return HttpUtils.PostFormDataFileThrowException(url, stream) as T;
        }

        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(5*60), ReportError);
#endif
                return waitAndRetryPolicy.Execute<BResult>(()=> UploadExportFileRetry<BResult>(result));
            }
            catch (Exception e)
            {
                Console.WriteLine($"Execute failed,Message:{e.Message}");
                return e.Message;
            }
        }
        static void ReportError(Exception e, TimeSpan timeSpan, int intento, Context context)
        {
            Console.WriteLine($"异常{intento:00} <调用秒数：{timeSpan.Seconds} 秒>\t 执行时间：{DateTime.Now}");
        }
    }
}
