package com.eactive.eai.custom.alarm.ums;

import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eactive.eai.common.util.Logger;
import com.eactive.eai.custom.alarm.ums.payload.UmsRequestPayload;

@Component
public class UmsSendManager {
    
    private final ScheduledExecutorService scheduler;

    protected static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
    
    Queue<UmsRequestPayload> queue = new ConcurrentLinkedQueue<UmsRequestPayload>();
 
    @Autowired
    UmsService umsService;
    
    public UmsSendManager() {
	this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
	    Thread t = new Thread(r);
	    t.setName("AlarmStateManager-worker");
	    t.setDaemon(false);
	    return t;
	});

	scheduler.scheduleWithFixedDelay(() -> {

	    try {
		// === 여기에 지속 실행할 로직 ===
		sendMessage();

	    } catch (Throwable e) {
		// 반드시 예외 잡기 (안 잡으면 스케줄 자체가 죽음)
		logger.error("fireAlarm fail", e);
	    }

	}, 0, 5, TimeUnit.SECONDS); // 최초 0초, 이후 5초 간격
    }
    
    void sendMessage() throws Exception {
	UmsRequestPayload payload;
        while ((payload = queue.poll()) != null) {
            final UmsRequestPayload finalPayload = payload;
            CompletableFuture.runAsync(() -> {
        	UmsCallResult result = null;
                try {
                    result = umsService.send(finalPayload);
                } catch (Exception e) {
                    logger.error("UMS 전송 실패", e);
                }finally {
                    logger.info(result);
                }
            });
        }
	
    }
    
    public void enqueue(UmsRequestPayload payload) {
        queue.offer(payload);
    }
    
    
}
