package eu.dnetlib.organizations.controller;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.common.controller.AbstractDnetController;
import eu.dnetlib.organizations.importer.ImportExecution;
import eu.dnetlib.organizations.importer.ImportExecutor;
import eu.dnetlib.organizations.utils.DatabaseUtils;

@RestController
@RequestMapping("/oa_api")
public class OpenaireInternalApiController extends AbstractDnetController {

	@Autowired
	private DatabaseUtils databaseUtils;

	@Value("${openaire.api.https.proxy}")
	private String httpsProxy;

	@Autowired
	private ImportExecutor importExecutor;

	private static final Log log = LogFactory.getLog(OpenaireInternalApiController.class);

	@GetMapping("/import/dedupEvents")
	public ImportExecution importDedupEvents(final HttpServletRequest req) {
		if (req.getRemoteAddr().equals(httpsProxy)) {
			log.warn("Call received by blaklisted ip (https proxy): " + req.getRemoteAddr());
			throw new RuntimeException("Call received by blaklisted ip (https proxy): " + req.getRemoteAddr());
		}

		return importExecutor.startImport("IP " + req.getRemoteAddr());
	}

	@GetMapping("/import/dedupEvents/status")
	public final ImportExecution statusDedupEvents(final HttpServletRequest req) {
		if (req.getRemoteAddr().equals(httpsProxy)) {
			log.warn("Call received by blaklisted ip (https proxy): " + req.getRemoteAddr());
			throw new RuntimeException("Call received by blaklisted ip (https proxy): " + req.getRemoteAddr());
		}
		return importExecutor.getLastImportExecution();
	}

	@GetMapping("/refresh/fulltextIndex")
	public final List<String> updateFulltextIndex(final HttpServletRequest req) {
		if (req.getRemoteAddr().equals(httpsProxy)) {
			log.warn("Call received by blaklisted ip (https proxy): " + req.getRemoteAddr());
			throw new RuntimeException("Call received by blaklisted ip (https proxy): " + req.getRemoteAddr());
		}
		new Thread(databaseUtils::updateFulltextIndex).start();

		return Arrays.asList("Updating ...");
	}

}
