using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace BanTur.Core.Utility
{
    public static class Aria2Helper
    {
        private static string GetNoticeFilePath(int id)
        {
            return Path.Combine(DbAccess.Config.WorkingDirectory, id + ".bat");
        }

        public static string GetLogFilePath(int id)
        {
            return Path.Combine(DbAccess.Config.WorkingDirectory, id + ".log");
        }

        public static string CreateNoticeFile(int id)
        {
            var self = Process.GetCurrentProcess().MainModule.FileName;
            var selfDir = Path.GetDirectoryName(self);
            var path = GetNoticeFilePath(id);
            var content = $"cd /d {selfDir}{Environment.NewLine}{self} {BanTurProgram.CmdComplete} {id} %3";
            if (Directory.Exists(DbAccess.Config.WorkingDirectory) == false) Directory.CreateDirectory(DbAccess.Config.WorkingDirectory);
            File.WriteAllText(path, content, Encoding.Default);
            return path;
        }

        public static void DeleteNoticeFile(int id)
        {
            var path = GetNoticeFilePath(id);
            File.Delete(path);
        }

        public static void StartBitTorrentDownload(string magnet, string downloadDirectory, string onBtDownloadComplete, string logFilePath)
        {
            if (Directory.Exists(downloadDirectory) == false) Directory.CreateDirectory(downloadDirectory);

            //TODO: set --follow-torrent=mem for http torrent url

            var p = new Process
            {
                StartInfo =
                {
                    FileName = "aria2c",
                    WorkingDirectory = downloadDirectory,
                    ArgumentList =
                    {
                        "--seed-time=30",
                        "--on-bt-download-complete=" + onBtDownloadComplete,
                        magnet
                    },
                    UseShellExecute = true,
                    WindowStyle = ProcessWindowStyle.Minimized,
                }
            };

            p.Start();
        }
    }
}