package com.inspect.job.task;

import com.alibaba.fastjson.JSONObject;
import com.inspect.base.redis.service.RedisService;
import com.inspect.job.client.PatrolVideoClient;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@EnableScheduling
@Component
public class PatrolVideoTask {
    private final int SECONDS = 10;
    private final RedisService redisService;
    private final PatrolVideoClient patrolVideoClient;
    private final String REDIS_LINKAGE_QUEUE_NOW = "REDIS_LINKAGE_QUEUE_NOW";
    private final String REDIS_LINKAGE_QUEUE = "REDIS_LINKAGE_QUEUE";
    private final String PATROL_RECORD = "PATROL_RECORD";

    public PatrolVideoTask(RedisService redisService, PatrolVideoClient patrolVideoClient) {
        this.redisService = redisService;
        this.patrolVideoClient = patrolVideoClient;
    }

    @Scheduled(
            cron = "0/20 * * * * ?"
    )
    public void videoBeatHeart() throws Exception {
        Map<String, Object> patrolRecord = this.redisService.redisTemplate.opsForHash().entries(PATROL_RECORD);
        for (String streamId : patrolRecord.keySet()) {
            Date date = (Date) patrolRecord.get(streamId);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.SECOND, -10);
            Calendar dateC = Calendar.getInstance();
            dateC.setTime(date);
            if (calendar.before(dateC)) {
                this.patrolVideoClient.record((new JSONObject()).fluentPut("streamId", streamId));
                this.redisService.redisTemplate.opsForHash().delete(PATROL_RECORD, streamId);
            }
        }

    }

    @Scheduled(
            cron = "0/1 * * * * ?"
    )
    public void linkageSignal() {
        if (!this.redisService.hasKey(REDIS_LINKAGE_QUEUE_NOW) &&
                this.redisService.redisTemplate.opsForList().size(REDIS_LINKAGE_QUEUE) > 0L) {
            this.redisService.setCacheObject(REDIS_LINKAGE_QUEUE_NOW, "1");
            this.redisService.expire(REDIS_LINKAGE_QUEUE_NOW, 5L, TimeUnit.MINUTES);
            this.patrolVideoClient.triggerLinkage();
        }

    }
}
