package cn.reghao.tnb.search.app.comment.service;

import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.jdk.string.SnowFlake;
import cn.reghao.tnb.auth.api.constant.TokenType;
import cn.reghao.tnb.auth.api.dto.AuthedAccount;
import cn.reghao.tnb.auth.api.iface.AccountQuery;
import cn.reghao.tnb.common.util.ConstantId;
import cn.reghao.tnb.content.api.dto.DanmakuSbtDto;
import cn.reghao.tnb.search.app.comment.db.mongo.UserDanmakuMongo;
import cn.reghao.tnb.search.app.comment.model.po.UserDanmaku;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author reghao
 * @date 2021-12-07 15:55:24
 */
@Service
public class DanmakuService {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private AccountQuery accountQuery;

    private final UserDanmakuMongo userDanmakuMongo;
    private final SnowFlake snowFlake;

    public DanmakuService(UserDanmakuMongo userDanmakuMongo) {
        this.snowFlake = new SnowFlake(1, 1);
        this.userDanmakuMongo = userDanmakuMongo;
    }

    public Result submit(DanmakuSbtDto danmakuSbtDto) {
        long loginUser = ConstantId.ANONYMOUS_USER_ID;
        String midHash = danmakuSbtDto.getMidHash();
        if (midHash == null) {
            String token = danmakuSbtDto.getToken();
            AuthedAccount authedAccount = accountQuery.getAuthedAccount(TokenType.token.getValue(), token);
            if (authedAccount == null) {
                return Result.fail("not auth");
            }

            loginUser = authedAccount.getUserId();
        }

        long dmId = snowFlake.nextId();
        UserDanmaku userDanmaku = new UserDanmaku(dmId, danmakuSbtDto, loginUser);
        userDanmakuMongo.save(userDanmaku);
        return Result.success();
    }

    public List<List<Object>> getByVideoIdAndSize(String videoId, int size) {
        List<List<Object>> list = new ArrayList<>();
        userDanmakuMongo.findByVideoId(videoId, size).forEach(danmakuRetVo -> {
            List<Object> list1 = new ArrayList<>();
            list1.add(danmakuRetVo.getTime());
            list1.add(danmakuRetVo.getType());
            list1.add(danmakuRetVo.getColor());
            list1.add(danmakuRetVo.getUserId());
            list1.add(danmakuRetVo.getText());
            list.add(list1);
        });
        return list;
    }
}
