package com.ycwl.basic.repository;

import cn.hutool.core.date.DateUtil;
import com.ycwl.basic.utils.JacksonUtil;
import com.ycwl.basic.mapper.TaskMapper;
import com.ycwl.basic.mapper.VideoMapper;
import com.ycwl.basic.model.pc.task.entity.TaskEntity;
import com.ycwl.basic.model.pc.task.resp.TaskRespVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Component
public class VideoTaskRepository {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private TaskMapper taskMapper;

    public static final String TASK_CACHE_KEY = "task:byId:%s";

    public TaskEntity getTaskById(Long taskId) {
        if (redisTemplate.hasKey(String.format(TASK_CACHE_KEY, taskId))) {
            return JacksonUtil.parseObject(redisTemplate.opsForValue().get(String.format(TASK_CACHE_KEY, taskId)), TaskEntity.class);
        } else {
            TaskEntity task = taskMapper.get(taskId);
            if (task != null && 1 == task.getStatus()) {
                redisTemplate.opsForValue().set(String.format(TASK_CACHE_KEY, taskId), JacksonUtil.toJSONString(task), 12, TimeUnit.HOURS);
            }
            return task;
        }
    }

    public void clearTaskCache(Long taskId) {
        redisTemplate.delete(String.format(TASK_CACHE_KEY, taskId));
    }


    public Date getTaskShotDate(Long taskId) {
        TaskRespVO taskRespVO = taskMapper.getById(taskId);
        if (taskRespVO == null) {
            return null;
        }
        Date shotTime = taskRespVO.getCreateTime();
        JacksonUtil.JSONObjectCompat paramJson = JacksonUtil.JSONObjectCompat.parseObject(taskRespVO.getTaskParams());
        if (paramJson != null) {
            Optional<String> any = paramJson.keySet().stream().filter(StringUtils::isNumeric).findAny();
            if (any.isPresent()) {
                var jsonArray = paramJson.getJSONArray(any.get());
                if (jsonArray != null && !jsonArray.isEmpty()) {
                    JacksonUtil.JSONObjectCompat jsonObject = jsonArray.get(0);
                    if (jsonObject.getString("createTime") != null) {
                        shotTime = DateUtil.parse(jsonObject.getString("createTime"));
                    }
                }
            }
        }
        return shotTime;
    }

}
