package com.ycwl.basic.repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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 JSONObject.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), JSONObject.toJSONString(task), 60 * 60 * 24L, TimeUnit.SECONDS);
            }
            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();
        JSONObject paramJson = JSON.parseObject(taskRespVO.getTaskParams());
        if (paramJson != null) {
            Optional<String> any = paramJson.keySet().stream().filter(StringUtils::isNumeric).findAny();
            if (any.isPresent()) {
                JSONArray jsonArray = paramJson.getJSONArray(any.get());
                if (!jsonArray.isEmpty()) {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    if (jsonObject.containsKey("createTime")) {
                        shotTime = new Date(jsonObject.getLong("createTime"));
                    }
                }
            }
        }
        return shotTime;
    }

}
