package com.github.novicezk.midjourney.service.store;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.github.novicezk.midjourney.enums.TaskStatus;
import com.github.novicezk.midjourney.service.TaskStoreService;
import com.github.novicezk.midjourney.support.Task;
import com.github.novicezk.midjourney.support.TaskCondition;
import com.github.novicezk.midjourney.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Date;
import java.util.List;

@Slf4j
public class InMemoryTaskStoreServiceImpl implements TaskStoreService {
	private final TimedCache<String, Task> taskMap;


	public InMemoryTaskStoreServiceImpl(Duration timeout) {
		this.taskMap = CacheUtil.newTimedCache(timeout.toMillis());
    }

	@Override
	public void save(Task task) {
		this.taskMap.put(task.getId(), task);
	}

	@Override
	public void delete(String key) {
		this.taskMap.remove(key);
	}

	@Override
	public Task get(String key) {
        FileUtil fileUtil = SpringUtil.getBean("fileUtil");
        Task task = this.taskMap.get(key);
        if(ObjectUtil.isNotNull(task)) {
            TaskStatus status = task.getStatus();
            if(TaskStatus.SUCCESS.equals(status) && StrUtil.isNotBlank(task.getImageUrl()) && task.getImageUrl().contains("cdn.discordapp.com")) {
                // 将discord地址转换成华为云地址返回
                task.setImageUrl(fileUtil.convertFile(task.getImageUrl()));
            }
            try {
                if(ObjectUtil.isNotNull(task.getFinishTime())) {
                    task.setFinishDate(DateUtil.formatDateTime(new Date(task.getFinishTime())));
                }
                if(ObjectUtil.isNotNull(task.getSubmitTime())) {
                    task.setSubmitDate(DateUtil.formatDateTime(new Date(task.getSubmitTime())));
                }
                if(ObjectUtil.isNotNull(task.getStartTime())) {
                    task.setStartDate(DateUtil.formatDateTime(new Date(task.getStartTime())));
                }
                Long costTime = (task.getFinishTime() - task.getStartTime()) / 1000;
                task.setCostTime(costTime);
            } catch (Exception e) {
                log.error("获取任务详情，转换图片异常：{}", key, e);
            }
        }
        return task;
	}

	@Override
	public List<Task> list() {
        List<Task> tasks = ListUtil.toList(this.taskMap.iterator());
        tasks.stream().forEach(x -> {
            try {
                x.setFinishDate(DateUtil.formatDateTime(new Date(x.getFinishTime())));
                x.setSubmitDate(DateUtil.formatDateTime(new Date(x.getSubmitTime())));
                x.setStartDate(DateUtil.formatDateTime(new Date(x.getStartTime())));
                Long costTime = (x.getFinishTime() - x.getStartTime()) / 1000;
                x.setCostTime(costTime);
            } catch (Exception e) {
            }
        });
        return ListUtil.toList(this.taskMap.iterator());
	}

	@Override
	public List<Task> list(TaskCondition condition) {
		return StreamUtil.of(this.taskMap.iterator()).filter(condition).toList();
	}

	@Override
	public Task findOne(TaskCondition condition) {
		return StreamUtil.of(this.taskMap.iterator()).filter(condition).findFirst().orElse(null);
	}

}
