package com.yutou.bilibili.services;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.bean.live.LiveRoomConfig;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.live.database.LiveDanmuDatabaseBean;
import com.yutou.biliapi.bean.live.database.LiveSuperChatDatabaseBean;
import com.yutou.biliapi.bean.live.database.LiveVideoDatabaseBean;
import com.yutou.biliapi.bean.websocket.live.WSData;
import com.yutou.biliapi.databases.BiliLiveConfigDatabase;
import com.yutou.biliapi.databases.BiliLiveDatabase;
import com.yutou.biliapi.net.WebSocketManager;
import com.yutou.bilibili.Tools.AssTools;
import com.yutou.bilibili.Tools.DateFormatUtils;
import com.yutou.bilibili.Tools.Tools;
import com.yutou.bilibili.datas.web.LiveVideoDanmu;
import com.yutou.common.utils.FFmpegUtils;
import com.yutou.common.utils.Log;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Service
public class LiveDanmuService {

    public void start(String roomId, boolean isUser) {
        WebSocketManager.getInstance().addRoom(LiveRoomConfig.buildConfig(roomId), isUser);
    }

    public boolean check(String roomId) {
        LiveRoomConfig roomConfig = new LiveRoomConfig();
        roomConfig.setRoomId(roomId);
        return WebSocketManager.getInstance().checkRoom(roomConfig);
    }

    public void stop(String roomId, boolean isUser) {
        WebSocketManager.getInstance().stopRoom(roomId, isUser);
    }

    public JSONArray getLiveRoomList() {
        return WebSocketManager.getInstance().getLiveRoomList();
    }

    public void clearUserList() {
        WebSocketManager.getInstance().clearUserStopList();
    }

    public List<File> getDanmuFileList(String roomId) {
        BiliLiveConfigDatabase configDatabase = new BiliLiveConfigDatabase();
        LiveConfigDatabaseBean bean = configDatabase.getConfig(roomId);
        configDatabase.close();
        return Tools.scanFile(new File(bean.getRecordPath() + File.separator + bean.getAnchorName()));
    }

    public void saveDanmuXML(LiveVideoDatabaseBean videoDatabaseBean, BiliLiveDatabase database) {
        File videoFile = new File(videoDatabaseBean.getPath());
        long videoTime;
        if (videoDatabaseBean.getStopTime() == null) {
            videoTime = System.currentTimeMillis();
        } else {
            videoTime = videoDatabaseBean.getStopTime().getTime();
        }
        Log.i("开始时间:" + videoDatabaseBean.getStartTime().getTime());
        Log.i("结束时间:" + videoTime);
        List<LiveDanmuDatabaseBean> danmus = database.getOfTime(videoDatabaseBean.getStartTime().getTime(), videoTime, LiveDanmuDatabaseBean.class);
        Log.i("弹幕数量:" + danmus.size());
        AssTools assTools = new AssTools(videoFile.getName().replace(".m3u8", ""), videoDatabaseBean.getStartTime());
        for (LiveDanmuDatabaseBean dm : danmus) {
            assTools.addDanmu(dm.createDanmuData());
        }
        assTools.saveDanmu(videoFile.getAbsolutePath().replace(".m3u8", ".ass"));
    }

    public String toTimeString(long videoTime) {
        long seconds = videoTime / 1000;
        long hours = seconds / 3600;
        long remainingSecondsAfterHours = seconds % 3600;
        long minutes = remainingSecondsAfterHours / 60;
        long finalRemainingSeconds = remainingSecondsAfterHours % 60;
//        long finalRemainingMilliseconds = videoTime % 1000;
        return String.format("%d小时%d分钟%d秒", hours, minutes, finalRemainingSeconds);
    }

    public LiveVideoDanmu getDanmu(String roomId, String videoId) {
        LiveVideoDanmu danmus = new LiveVideoDanmu();
        BiliLiveDatabase liveDatabase = new BiliLiveDatabase(LiveRoomConfig.buildConfig(roomId));
        LiveVideoDatabaseBean videoBean = liveDatabase.getVideo(videoId);
        if (videoBean == null) {
            return new LiveVideoDanmu();
        }
        long startTime = Long.parseLong(videoId);
        long endTime = videoBean.getStopTime() == null ? System.currentTimeMillis() : videoBean.getStopTime().getTime();
        List<LiveDanmuDatabaseBean> danmuList = liveDatabase.getOfTime(startTime, endTime, LiveDanmuDatabaseBean.class);
        List<LiveSuperChatDatabaseBean> superChatList = liveDatabase.getOfTime(startTime, endTime, LiveSuperChatDatabaseBean.class);
        for (LiveDanmuDatabaseBean bean : danmuList) {
            LiveVideoDanmu.Danmu danmu = createDanmu(bean, startTime);
            danmus.getDanmu().add(danmu);
        }
        for (LiveSuperChatDatabaseBean bean : superChatList) {
            LiveVideoDanmu.SuperChat superChat = new LiveVideoDanmu.SuperChat(startTime, bean);
            danmus.getSuperChat().add(superChat);
        }

        liveDatabase.close();
        return danmus;
    }

    @NotNull
    private static LiveVideoDanmu.Danmu createDanmu(LiveDanmuDatabaseBean bean, long startTime) {
        LiveVideoDanmu.Danmu danmu = new LiveVideoDanmu.Danmu();
        danmu.setId(bean.getId() + "");
        danmu.setText(bean.getDanmu());
        danmu.setColor("#" + bean.getFontColor());
        danmu.setFontSize(bean.getFontSize());
        danmu.setTime(bean.getTime() - startTime);
        if (bean.getModel() < 4) {
            danmu.setBarrageType(LiveVideoDanmu.Danmu.DANMU_TYPE_SCROLL);
        } else if (bean.getModel() == 4) {
            danmu.setBarrageType(LiveVideoDanmu.Danmu.DANMU_TYPE_BOTTOM);
        } else if (bean.getModel() == 5) {
            danmu.setBarrageType(LiveVideoDanmu.Danmu.DANMU_TYPE_TOP);
        }
        return danmu;
    }

    public static void main(String[] args) {
        BiliLiveDatabase database = new BiliLiveDatabase(LiveRoomConfig.buildConfig("17961"));
        for (LiveVideoDatabaseBean info : database.getLiveInfos()) {
            System.out.println(info);
        }
        WSData data = WSData.parse(JSONObject.parseObject("{\"cmd\":\"GUARD_BUY\",\"data\":{\"uid\":290721462,\"username\":\"BG7NOE型大地鱼干\",\"guard_level\":3,\"num\":1,\"price\":198000,\"gift_id\":10003,\"gift_name\":\"舰长\",\"start_time\":1730462544,\"end_time\":1730462544}}"));
        System.out.println(data);
    }


}
