package com.yutou.nas.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

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",PatternTools.getMagnetHash(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);
            return true;
        } 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);
        System.out.println("path = " + path + ", filename = " + filename + ", hash1 = " + hash1 + ", hash2 = " + hash2 + ", tid = " + tid);
        String hash=StringUtils.isEmpty(hash1)?StringUtils.isEmpty(hash2)?null:hash2:hash1;
        if(hash!=null){
            String map = RedisTools.getHashMap("rss", hash);
            System.out.println("map = " + map);
            JSONObject item=JSON.parseObject(map);
            if (item.containsKey("thumbnail")) {
                onSend(item.getString("thumbnail"), item,item.getJSONObject("enclosure").getString("link"));
            } else {
                onSend(null, item,item.getJSONObject("enclosure").getString("link"));
            }
        }
    }

    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);
    }
}
