package gov.va.vss.web;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import gov.va.vss.model.printing.DeferredPrintResult;
import gov.va.vss.service.scheduledJobs.PrintRequestDistributionJob;

@RestController
public class PrintServiceController extends AbstractKioskController {
	private static final Logger log = LoggerFactory.getLogger(PrintServiceController.class);

	@Autowired
	private PrintRequestDistributionJob distributionJob;

	@RequestMapping("/getNextPrintRequest")
	public @ResponseBody DeferredPrintResult getNextPrintRequest(@RequestParam long kioskId, HttpSession session) {
		session.setMaxInactiveInterval(0);
		DeferredPrintResult kioskResult = distributionJob.getSuspendedPrintJobsMap().computeIfAbsent(kioskId,
				k -> new DeferredPrintResult(1000 * 60 * 30L, new ArrayList<>()));

		kioskResult.onCompletion(new Runnable() {
			@Override
			public void run() {
				log.info("Removing print request for kiosk ID {} from queue", kioskId);
				distributionJob.getSuspendedPrintJobsMap().remove(kioskId);
			}
		});

		return kioskResult;
	}

}
