package com.caliverse.admin.scheduler;

import com.caliverse.admin.domain.entity.InGame;
import com.caliverse.admin.domain.entity.Mail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
@Slf4j
public class ScheduleService {

    private final Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();

    private final Map<Long, Mail> mailTask = new ConcurrentHashMap<>();
    private final Map<Long, InGame> noticeTask = new ConcurrentHashMap<>();

    private static final int MAX_MAIL_TASKS = 500;
    private static final int MAX_NOTICE_TASKS = 500;

    public boolean isTaskExist(String key){
        return scheduledTasks.containsKey(key);
    }

    public void addTask(String key, ScheduledFuture<?> schdule){
        scheduledTasks.put(key, schdule);
    }

    public void closeTask(String key) {
        ScheduledFuture<?> scheduledFuture = scheduledTasks.get(key);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledTasks.remove(key);
        }
    }

    public void cleanupCompletedTasks() {
        try {
            Iterator<Map.Entry<String, ScheduledFuture<?>>> iterator = scheduledTasks.entrySet().iterator();
            int removedCount = 0;

            while (iterator.hasNext()) {
                Map.Entry<String, ScheduledFuture<?>> entry = iterator.next();
                ScheduledFuture<?> future = entry.getValue();

                if (future.isDone() || future.isCancelled()) {
                    iterator.remove();
                    removedCount++;
                }
            }

            if (removedCount > 0) {
                log.info("Cleaned up {} completed scheduled tasks. Current task count: {}",
                        removedCount, scheduledTasks.size());
            }
        } catch (Exception e) {
            log.error("Error during cleanup of completed tasks", e);
        }
    }

    public void cleanupMailTasks() {
        if (mailTask.size() > MAX_MAIL_TASKS) {
            int toRemove = mailTask.size() - MAX_MAIL_TASKS;
            Iterator<Long> iterator = mailTask.keySet().iterator();
            int removed = 0;

            while (iterator.hasNext() && removed < toRemove) {
                iterator.next();
                iterator.remove();
                removed++;
            }

//            log.info("Cleaned up {} mail tasks due to size limit", removed);
        }
    }

    public void cleanupNoticeTasks() {
        if (noticeTask.size() > MAX_NOTICE_TASKS) {
            int toRemove = noticeTask.size() - MAX_NOTICE_TASKS;
            Iterator<Long> iterator = noticeTask.keySet().iterator();
            int removed = 0;

            while (iterator.hasNext() && removed < toRemove) {
                iterator.next();
                iterator.remove();
                removed++;
            }

//            log.info("Cleaned up {} notice tasks due to size limit", removed);
        }
    }

}
