using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CheckServer
{
    /// 
    /// 变采样帮助类
    /// 
    public static class ReSampleHelper
    {
        private static string exePath = "AddIns";
        private const string exeName = "ReSample.exe";
        /// 
        /// 设置【ReSample.exe】文件所在路径,支持相对路径
        /// 
        public static void SetExePath(string path)
        {
            if (string.IsNullOrWhiteSpace(path)) return;
            if (path.StartsWith("\\"))//相对路径要么开头不带\,要么是 .\
                path = path.Remove(0, 1);
            exePath = path;
        }
        /// 
        /// 变采样
        /// 
        /// 输入文件
        /// 输出文件
        /// 插入因子
        /// 抽取因子
        /// 超时时间
        /// 成功后返回文件,失败后返回null
        public static string Resample(string inFile, string outFile, int insertFactor, int extFactor, int timeoutSeconds = 30)
        {
            if (string.IsNullOrWhiteSpace(exePath))
                throw new Exception($"请先调用SetExePath指定{exeName}进程所在路径,支持相对路径");
            if (!Directory.Exists(exePath))
                throw new Exception($"路径[{exePath}]不存在");
            var exeFile = Path.Combine(exePath, exeName);
            if (!File.Exists(exeFile))
                throw new Exception($"文件[{exeFile}]不存在");
            Process p = new Process();
            p.StartInfo.WorkingDirectory = exePath;
            p.StartInfo.FileName = exeFile;
            p.StartInfo.Arguments = $"\"{inFile}\" \"{outFile}\" {insertFactor} {extFactor}";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.Start();
            var succeed = p.WaitForExit(timeoutSeconds * 1000);
            if (!succeed)
            {
                throw new Exception($"进程[{exeName}]超时未完成!");
            }
            var res = p.StandardOutput.ReadToEnd();
            if (res.StartsWith("1:"))
            {
                return outFile;
            }
            else
            {
                return null;
            }
        }
    }
}