package com.yutou.nas.Controllers;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.nas.Services.IBangumiService;
import com.yutou.nas.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Controller
public class BTDownloadController {
    @Resource
    IBangumiService bangumiService;

    @ResponseBody
    @RequestMapping("/bt/down.do")
    public String bt() {
        DmhyRssDownloadManager.getInstance().start();
        AnimRssManager.scan();
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/bt/done.do")
    public String done(String path, String filename, String hash1, String hash2, String tid) {
        Log.i("BTDownloadController.done", "path = " + path + ", filename = " + filename + ", hash1 = " + hash1 + ", hash2 = " + hash2 + ", tid = " + tid);
        //BTDownloadManager.done(path, filename, hash1, hash2, tid);
        try {
            String exec = ConfigTools.load(ConfigTools.CONFIG, "tiny.exec", String.class);
            Process process = Runtime.getRuntime().exec(new String[]{"sh"
                    , "-c"
                    , exec});
            process.waitFor(120, TimeUnit.SECONDS);
        } catch (Exception e) {
            Log.e("下崽器", e);
        }

        return "ok";
    }

    @ResponseBody
    @RequestMapping("/bt/download.do")
    public String download(int id, boolean isDownloadNext, String url) {
        Log.i("跳过下载", "手动下载 id = " + id + ", isDownloadNext = " + isDownloadNext + ", url = " + url);
        bangumiService.download(id, isDownloadNext, url);
        return "1";
    }

    @ResponseBody
    @RequestMapping("/qq/bt/download.do")
    public String download(HttpServletRequest request) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String title = null;
        String url = null;
        try {
            BufferedInputStream stream = new BufferedInputStream(request.getInputStream());
            byte[] bytes = new byte[1024];
            int len = 0, size;
            while ((len = stream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            String str = outputStream.toString();
            JSONObject json = JSONObject.parseObject(str);
            title = json.getString("title");
            url = json.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("QQ下载", "手动下载 title = " + title + ", url = " + url);
        return "" + BTDownloadManager.download(title, url);
    }
}
