package com.yutou.bilibili.BiliBili.Controllers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.bilibili.BiliBili.LiveUtils;
import com.yutou.bilibili.BiliBili.Services.IBiliBiliLiveService;
import com.yutou.bilibili.BiliBili.Tools.BiliTools;
import com.yutou.bilibili.Services.ISystemConfigService;
import com.yutou.bilibili.Services.IUserService;
import com.yutou.bilibili.Tools.*;
import com.yutou.bilibili.mybatis.Bili.mybatis.model.BilibiliUpInfo;
import com.yutou.bilibili.mybatis.model.UUser;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
public class BiliVideoController {
    @Resource
    IUserService service;
    @Resource
    IBiliBiliLiveService liveService;
    @Resource
    ISystemConfigService configService;

    @ResponseBody
    @RequestMapping("/bili/video/get/list.do")
    public JSONObject videoList(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String token = AppTools.getLoginToken(request);
        UUser user = service.getUserToToken(token);
        if (user == null) {
            json.put("code", -1);
            json.put("msg", "未登录");
            json.put("data", new JSONObject());
            return json;
        }
        if (ServiceTools.getInstance().auth(request, user.getUser(), "/bili/video/get/")) {
            File file = new File(ConfigTools.load(ConfigTools.CONFIG,"liveSavePath",String.class));
            Log.i(file.getAbsolutePath());
            if (!file.exists() || Objects.requireNonNull(file.listFiles()).length == 0) {
                json.put("code", 0);
                json.put("msg", "文件夹为空");
                json.put("data", new JSONObject());
            } else {
                List<File> list = AppTools.scanFilePath(file.getAbsolutePath()+File.separator+"live");
                JSONArray array = new JSONArray();
                for (File f : list) {
                    JSONObject item = new JSONObject();
                    String _time = f.getName().split(" ")[0].substring(1);
                    File mpeg = new File("ffmpeg_out" + File.separator + _time + File.separator + f.getName());
                    if (mpeg.exists()) {
                        f = mpeg;
                        item.put("ffmpeg", true);
                    } else {
                        item.put("ffmpeg", false);
                    }
                    String date = f.getName().split(" ")[0].substring(1);
                    String time = f.getName().split(" ")[1].split("\\]")[0];
                    String roomid = f.getName().split("\\]")[1].replace(".mp4", "").replace("_ffmpeg", "").trim();

                    BilibiliUpInfo info = liveService.queryUpToRoomId(Integer.parseInt(roomid));
                    long size = f.length();
                    String _size;
                    if (size < 1024) {
                        _size = size + "B";
                    } else if (size < 1048576) {
                        _size = (size / 1024) + "KB";
                    } else if (size < 1073741824) {
                        _size = (size / 1048576) + "MB";
                    } else {
                        _size = (size / 1073741824) + "GB";
                    }

                    item.put("fileName", f.getName());
                    item.put("fileSize", _size);
                    item.put("date", date);
                    item.put("time", time);
                    item.put("name", info == null ? roomid : info.getName());
                    array.add(item);
                }
                json.put("code", 0);
                json.put("msg", "ok");
                json.put("data", array);
            }
        } else {
            json.put("code", -2);
            json.put("msg", "未授权");
            json.put("data", new JSONObject());
        }
        return json;
    }

    @RequestMapping("/bili/video/download/get.do")
    public ResponseEntity<FileSystemResource> download(String fileName) {
        String time = fileName.split(" ")[0].substring(1);
        File file = new File("ffmpeg_out" + File.separator + time + File.separator + fileName);
        if (!file.exists()) {
            file = new File(ConfigTools.load(ConfigTools.CONFIG,"liveSavePath",String.class)+File.separator+"live" + File.separator + time + File.separator + fileName);
        }
        Log.i(file.getAbsolutePath());
        return AppTools.getFile(file);
    }
    @ResponseBody
    @RequestMapping("/bili/video/set/ffmpeg.do")
    public JSONObject ffmpegOut(String fileName) throws UnsupportedEncodingException {
        fileName= URLDecoder.decode(fileName,"UTF-8");
        JSONObject json=new JSONObject();
        json.put("code",0);
        json.put("msg","ok");
        String time = fileName.split(" ")[0].substring(1);
        File file = new File("live" + File.separator + time + File.separator + fileName);
        System.out.println("file "+file.getAbsolutePath()+" "+file.exists());
        String ffmpeg=configService.getConfig(Config.SYSTEM_VIDEO_FFMPEG);
        if(StringUtils.isEmpty(ffmpeg)||!new File(ffmpeg).exists()){
            json.put("msg","FFmpeg未设置，请联系管理员");
            return json;
        }
        int i= FFmpegUtils.add(configService.getConfig(Config.SYSTEM_VIDEO_FFMPEG),file,new File("ffmpeg_out"+File.separator+time));
        json.put("model",i);
        switch (i){
            case 0:
                json.put("msg","已添加到后台转码");
                break;
            case 1:
                json.put("msg","已经转码，无须二次转码");
                break;
            case 2:
                json.put("msg","正在转码");
                break;
        }
        return json;
    }
}
