package com.yutou.nas.utils;

import com.acgist.snail.Snail;
import com.acgist.snail.context.ProtocolContext;
import com.acgist.snail.context.TaskContext;
import com.acgist.snail.context.exception.DownloadException;
import com.acgist.snail.pojo.ITaskSession;
import com.acgist.snail.protocol.magnet.MagnetProtocol;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class BTDownloadManager {
    protected static final String DownloadHomePath = "/media/yutou/disk_lvm/public/download/";

    public synchronized static boolean skipDownload(String title, JSONObject json) {
        if ("ok".equals(json.getString("status"))) {
            JSONArray items = json.getJSONArray("items");
            for (Object _item : items) {
                JSONObject item = (JSONObject) _item;
                if (!isDownload(title, item.getString("title"))) {
                    JSONArray array = getDownload(title);
                    array.add(item.getString("title"));
                    RedisTools.set(title, array.toJSONString());
                    Log.i("跳过下载", title);
                    return true;
                }
            }
        }
        return false;
    }

    public synchronized static void download(String title, JSONObject json) {
        if ("ok".equals(json.getString("status"))) {
            JSONArray items = json.getJSONArray("items");
            for (Object _item : items) {
                JSONObject item = (JSONObject) _item;
                //确认是为下载过的
                if (!isDownload(title, item.getString("title"))) {
                    //添加到下载器
                    if (download(title, item.getJSONObject("enclosure").getString("link"))) {
                        //发通知到QQ
                        RedisTools.setHashMap("rss", getTorrentFileHash(item.getJSONObject("enclosure").getString("link")), item.toJSONString());
                        JSONArray array = getDownload(title);
                        array.add(item.getString("title"));
                        RedisTools.set(title, array.toJSONString());
                        if (item.containsKey("thumbnail")) {
                            onSend(item.getString("thumbnail"), item, item.getJSONObject("enclosure").getString("link"));
                        } else {
                            onSend(null, item, item.getJSONObject("enclosure").getString("link"));
                        }
                    } else {
                        Log.i("BT", "添加到下载器失败:" + item.getString("title"));
                    }
                } else {
                    Log.i("BT", "已下载过:" + item.getString("title"));
                }
            }
        } else {
            Log.i("BT", "rss2json转换失败:" + title);
        }
    }

    private static void onSend(String fileUrl, JSONObject item, String url) {
        String text = "启动下载器\n已提交到下载:" + item.getString("title");
        Log.i(text);
        if (fileUrl == null) {
            QQBotManager.getInstance().sendMessage(text);
        } else {
            QQBotManager.getInstance().sendMessage(fileUrl, text);
        }
        //RedisTools.set(item.getString("title"),url);
    }

    public static boolean download(String title, String url) {
        try {
          /*  String exec = String.format("qbittorrent-nox  --save-path=\"%sanim/%s\" \"%s\""
                    , DownloadHomePath
                    , title
                    , url
            );
            Log.i(exec);
            Process process = Runtime.getRuntime().exec(new String[]{"sh"
                    , "-c"
                    , exec});
            process.waitFor(120, TimeUnit.SECONDS);*/
            JSONObject json = new JSONObject();
            json.put("urls", url);
            json.put("savepath", "anim/" + title);

            String data="urls="+url+"&savepath=anim/"+title;
            String post = HttpTools.http_post_form(
                    ConfigTools.load(ConfigTools.CONFIG, "Qbittorrent.Url", String.class) + "/api/v2/torrents/add",
                    data.getBytes(StandardCharsets.UTF_8),
                    0,
                    null
            );
            Log.i("BT下载", post);
            return post.toLowerCase().contains("ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static JSONArray getDownload(String title) {
        String _title = RedisTools.get(title);
        if (StringUtils.isEmpty(_title)) {
            return new JSONArray();
        }
        return JSON.parseArray(_title);
    }

    private static boolean isDownload(String title, String key) {
        String _title = RedisTools.get(title);
        JSONArray array;
        if (StringUtils.isEmpty(_title)) {
            return false;
        } else {
            array = JSON.parseArray(_title);
        }
        return array.contains(key);
    }

    public synchronized static void done(String path, String filename, String hash1, String hash2, String tid) {
        grep(path, filename);
        String hash = StringUtils.isEmpty(hash1) ? StringUtils.isEmpty(hash2) ? null : hash2 : hash1;
        if (hash != null) {
            String map = RedisTools.getHashMap("rss", hash);
            JSONObject item = JSON.parseObject(map);
            String text = "添加到库:" + item.getString("title") + "\n动漫花园地址:" + item.getString("link");
            if (!item.containsKey("thumbnail")) {
                QQBotManager.getInstance().sendMessage(734332887, text);
            } else {
                QQBotManager.getInstance().sendMessage(734332887, item.getString("thumbnail"), text);
            }
        }
    }

    private static void grep(String remoteLocation, String remoteName) {
       /* if(remoteName.contains("265")){
            String newName=remoteName.replace("265","贰陸伍");
            String exec="mv \"" + remoteLocation + File.separator + remoteName + "\" \"" + remoteLocation + File.separator + newName+"\"";
            Log.i("执行改名",exec);
            AppTools.exec(exec, new ObjectInterface() {
                @Override
                public void out(String data) {
                    super.out(data);
                    Log.i("改名结果：",data);
                }
            }, false, true);
        }*/
        //AppTools.exec("/home/yutou/public/servier/tinyMediaManager/tinyMediaManager tvshow -u --scrapeUnscraped", null, false, true);
        //   AppTools.exec("/home/yutou/public/servier/tinyMediaManager/tinyMediaManager tvshow -u -w --scrapeUnscraped", null, false, true);//由系统脚本处理
    }

    public static String getTorrentFileHash(String magnet) {
        String hash = null;
        try {
            ProtocolContext.getInstance().register(MagnetProtocol.getInstance());
            ITaskSession session = ProtocolContext.getInstance().buildTaskSession(magnet);
            hash = session.getName();
            Tools.delDir("download");
        } catch (DownloadException e) {
            e.printStackTrace();
        }
        return hash;
    }

    public static void main(String[] args) {
        File file = new File("[织梦字幕组]与猫共度的夜晚 夜は猫といっしょ[17][第十七夜][GB_JP][AVC][1080P].mp4.torrent");
        //Snail snail = Snail.SnailBuilder.newBuilder().enableAllProtocol().buildSync();
        try {
            ProtocolContext.getInstance().register(MagnetProtocol.getInstance());
            ITaskSession session = ProtocolContext.getInstance().buildTaskSession("magnet:?xt=urn:btih:IQ4GD4AYEJP3PSLB26QTLUP27UDQ4RRX&dn=&tr=http%3A%2F%2F104.143.10.186%3A8000%2Fannounce&tr=udp%3A%2F%2F104.143.10.186%3A8000%2Fannounce&tr=http%3A%2F%2Ftracker.openbittorrent.com%3A80%2Fannounce&tr=http%3A%2F%2Ftracker3.itzmx.com%3A6961%2Fannounce&tr=http%3A%2F%2Ftracker4.itzmx.com%3A2710%2Fannounce&tr=http%3A%2F%2Ftracker.publicbt.com%3A80%2Fannounce&tr=http%3A%2F%2Ftracker.prq.to%2Fannounce&tr=http%3A%2F%2Fopen.acgtracker.com%3A1096%2Fannounce&tr=https%3A%2F%2Ft-115.rhcloud.com%2Fonly_for_ylbud&tr=http%3A%2F%2Ftracker1.itzmx.com%3A8080%2Fannounce&tr=http%3A%2F%2Ftracker2.itzmx.com%3A6961%2Fannounce&tr=udp%3A%2F%2Ftracker1.itzmx.com%3A8080%2Fannounce&tr=udp%3A%2F%2Ftracker2.itzmx.com%3A6961%2Fannounce&tr=udp%3A%2F%2Ftracker3.itzmx.com%3A6961%2Fannounce&tr=udp%3A%2F%2Ftracker4.itzmx.com%3A2710%2Fannounce&tr=http%3A%2F%2Ftr.bangumi.moe%3A6969%2Fannounce&tr=http%3A%2F%2Ft.nyaatracker.com%2Fannounce&tr=http%3A%2F%2Fopen.nyaatorrents.info%3A6544%2Fannounce&tr=http%3A%2F%2Ft2.popgo.org%3A7456%2Fannonce&tr=http%3A%2F%2Fshare.camoe.cn%3A8080%2Fannounce&tr=http%3A%2F%2Fopentracker.acgnx.se%2Fannounce&tr=http%3A%2F%2Ftracker.acgnx.se%2Fannounce&tr=http%3A%2F%2Fnyaa.tracker.wf%3A7777%2Fannounce&tr=http%3A%2F%2Fsukebei.tracker.wf%3A8888%2Fannounce&tr=http%3A%2F%2Ft.acg.rip%3A6699%2Fannounce&tr=https%3A%2F%2Ftr.bangumi.moe%3A9696%2Fannounce&tr=http%3A%2F%2Ftracker.opentrackr.org%3A1337%2Fannounce&tr=wss%3A%2F%2Ftracker.openwebtorrent.com%3A443%2Fannounce&tr=http%3A%2F%2F1337.abcvg.info%2Fannounce&tr=http%3A%2F%2F207.241.226.111%3A6969%2Fannounce&tr=http%3A%2F%2F207.241.231.226%3A6969%2Fannounce&tr=http%3A%2F%2F%5B2001%3A1b10%3A1000%3A8101%3A0%3A242%3Aac11%3A2%5D%3A6969%2Fannounce&tr=http%3A%2F%2F%5B2001%3A470%3A1%3A189%3A0%3A1%3A2%3A3%5D%3A6969%2Fannounce&tr=http%3A%2F%2F%5B2a04%3Aac00%3A1%3A3dd8%3A%3A1%3A2710%5D%3A2710%2Fannounce&tr=http%3A%2F%2Fbt.okmp3.ru%3A2710%2Fannounce&tr=http%3A%2F%2Ffxtt.ru%2Fannounce&tr=http%3A%2F%2Fhome.yxgz.vip%3A6969%2Fannounce&tr=http%3A%2F%2Fmediaclub.tv%2Fannounce.php&tr=http%3A%2F%2Fmilanesitracker.tekcities.com%2Fannounce&tr=http%3A%2F%2Fopen.acgnxtracker.com%2Fannounce&tr=http%3A%2F%2Fopen.tracker.ink%3A6969%2Fannounce&tr=http%3A%2F%2Fopentracker.i2p.rocks%3A6969%2Fannounce&tr=http%3A%2F%2Fopentracker.xyz%2Fannounce&tr=http%3A%2F%2Fretracker.hotplug.ru%3A2710%2Fannounce&tr=http%3A%2F%2Ft.overflow.biz%3A6969%2Fannounce&tr=http%3A%2F%2Ft.publictracker.xyz%3A6969%2Fannounce&tr=http%3A%2F%2Ftorrenttracker.nwc.acsalaska.net%3A6969%2Fannounce&tr=http%3A%2F%2Ftr.cili001.com%3A8070%2Fannounce&tr=http%3A%2F%2Ftracker.birkenwald.de%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.bt4g.com%3A2095%2Fannounce&tr=http%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.files.fm%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.gbitt.info%2Fannounce&tr=http%3A%2F%2Ftracker.hiyj.cn%2Fannounce&tr=http%3A%2F%2Ftracker.ipv6tracker.ru%2Fannounce&tr=http%3A%2F%2Ftracker.lelux.fi%2Fannounce&tr=http%3A%2F%2Ftracker.mywaifu.best%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.srv00.com%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.zerobytes.xyz%3A1337%2Fannounce&tr=http%3A%2F%2Ftracker2.dler.org%2Fannounce&tr=http%3A%2F%2Fvps02.net.orel.ru%2Fannounce&tr=https%3A%2F%2F1337.abcvg.info%2Fannounce&tr=https%3A%2F%2Fcarbon-bonsai-621.appspot.com%2Fannounce&tr=https%3A%2F%2Fchihaya-heroku.120181311.xyz%2Fannounce&tr=https%3A%2F%2Fopentracker.cc%2Fannounce&tr=https%3A%2F%2Fopentracker.i2p.rocks%2Fannounce&tr=https%3A%2F%2Ftp.m-team.cc%2Fannounce.php&tr=https%3A%2F%2Ftr.abiir.top%2Fannounce&tr=https%3A%2F%2Ftr.abir.ga%2Fannounce&tr=https%3A%2F%2Ftr.abirxo.cf%2Fannounce&tr=https%3A%2F%2Ftr.burnabyhighstar.com%2Fannounce&tr=https%3A%2F%2Ftr.doogh.club%2Fannounce&tr=https%3A%2F%2Ftr.fuckbitcoin.xyz%2Fannounce&tr=https%3A%2F%2Ftr.highstar.shop%2Fannounce&tr=https%3A%2F%2Ftr.ready4.icu%2Fannounce&tr=https%3A%2F%2Ftr.torland.ga%2Fannounce&tr=https%3A%2F%2Ftracker.babico.name.tr%2Fannounce&tr=https%3A%2F%2Ftracker.imgoingto.icu%2Fannounce&tr=https%3A%2F%2Ftracker.iriseden.fr%2Fannounce&tr=https%3A%2F%2Ftracker.kuroy.me%2Fannounce&tr=https%3A%2F%2Ftracker.lelux.fi%2Fannounce&tr=https%3A%2F%2Ftracker.lilithraws.cf%2Fannounce&tr=https%3A%2F%2Ftracker.lilithraws.org%2Fannounce&tr=https%3A%2F%2Ftracker.nanoha.org%2Fannounce&tr=https%3A%2F%2Ftracker.nitrix.me%2Fannounce&tr=https%3A%2F%2Ftracker.yarr.pt%2Fannounce&tr=https%3A%2F%2Ftrackme.theom.nz%2Fannounce&tr=ws%3A%2F%2Fhub.bugout.link%3A80%2Fannounce&tr=http%3A%2F%2Fretracker.joxnet.ru%2Fannounce&tr=http%3A%2F%2Ftracker.openbittorrent.com%2Fannounce&tr=http%3A%2F%2Ftracker.skyts.net%3A6969%2Fannounce&tr=https%3A%2F%2Fabir0dev.github.io%2Fannounce&tr=https%3A%2F%2Ftracker.foreverpirates.co%2Fannounce&tr=http%3A%2F%2Ftracker.loadbt.com%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.swarm3.network%3A6969%2Fannounce&tr=http%3A%2F%2Fopenbittorrent.com%2Fannounce&tr=http%3A%2F%2Fpow7.com%2Fannounce&tr=http%3A%2F%2Fbuny.uk%3A6969%2Fannounce&tr=http%3A%2F%2Ffosstorrents.com%3A6969%2Fannounce&tr=http%3A%2F%2Fftp.pet%3A7777%2Fannounce&tr=http%3A%2F%2Frt.optizone.ru%2Fannounce&tr=http%3A%2F%2Ftracker.merded.xyz%3A8000%2Fannounce&tr=http%3A%2F%2Ftracker1.bt.moack.co.kr%2Fannounce&tr=https%3A%2F%2Ftracker.moeblog.cn%2Fannounce&tr=https%3A%2F%2Ftracker.tamersunion.org%2Fannounce&tr=http%3A%2F%2Fipv6.1337.cx%3A6969%2Fannounce&tr=http%3A%2F%2Fipv6.govt.hu%3A6969%2Fannounce&tr=http%3A%2F%2Ftracker.k.vu%3A6969%2Fannounce&tr=https%3A%2F%2Ftracker.feb217.tk%3A8443%2Fannounce&tr=https%3A%2F%2Ftracker.m-team.cc%2Fannounce.php");
            System.out.println(session.getName());
            Tools.delDir("download");
        } catch (DownloadException e) {
            throw new RuntimeException(e);
        }
    }
}
