package com.yutou.bilibili.Controllers;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.bilibili.Tools.FileServerUtils;
import com.yutou.bilibili.Tools.Tools;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.bilibili.datas.VideoFilePath;
import com.yutou.bilibili.services.LiveVideoDownloadService;
import com.yutou.common.okhttp.HttpDownloadUtils;
import com.yutou.common.utils.AppTools;
import com.yutou.common.utils.Log;
import jakarta.annotation.Resource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

@Controller
public class VideoFileController {
    @Resource
    LiveVideoDownloadService videoService;

    @ResponseBody
    @RequestMapping("/file/list")
    public JSONObject getFileList(int page, int limit, String roomId) {
        return ResultData.success(videoService.getVideoPath(roomId));
    }

    @RequestMapping("/file/{base64}")
    @ResponseBody
    public ResponseEntity<FileSystemResource> getFile(@PathVariable String base64) {
        File file = FileServerUtils.toFile(base64);
        Log.i(file.getAbsolutePath());
        return Tools.getFile(file);
    }

    @RequestMapping(value = "/file/img", method = RequestMethod.POST)
    public ResponseEntity<FileSystemResource> getImg(String url) {
        url = URLDecoder.decode(url, StandardCharsets.UTF_8);
        String encode = AppTools.getMD5(url);
        File img = new File("cache" + File.separator + "image" + File.separator + encode);
        int length;
        try {
            length = new URL(url).openConnection().getContentLength();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (img.exists()&&length==img.length()) {
            return Tools.getFile(img);
        }
        if (!img.getParentFile().exists()) {
            img.getParentFile().mkdirs();
        }
        File file = HttpDownloadUtils.downloadSync(new HttpDownloadUtils.Builder()
                .setFileName(encode)
                .setUrl(url)
                .setPath(img.getParent())
        );
        if (file != null) {
            return Tools.getFile(file);
        }
        return null;
    }

    @RequestMapping(value = "/file/imgTmp", method = RequestMethod.POST)
    @ResponseBody
    public String getTmpImg(String url) {
        try {
            // 获取图片流
            InputStream inputStream = new URL(url).openStream();

            // 将输入流转换为字节数组
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
            byte[] imageBytes = byteArrayOutputStream.toByteArray();

            // 关闭输入流
            inputStream.close();
            byteArrayOutputStream.close();

            // 将字节数组编码为 Base64 字符串
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);

            // 返回带有 MIME 类型的数据 URI
            return base64Image;
        } catch (Exception ignored) {
            return "/assets/def.png";
        }
    }

    @RequestMapping("/video/play")
    @ResponseBody
    public JSONObject getVideoUrl(String roomId, String videoId) {
        String url = videoService.getVideoPlay(roomId, videoId);
       /* String[] split = url.split("/");
        StringBuilder sb=new StringBuilder();
        for (String s : split) {
            sb.append(URLEncoder.encode(s,StandardCharsets.UTF_8)).append("/");
        }
        sb.setLength(sb.length()-1);*/
        return ResultData.success("/live"+url);
    }
}
