package org.minager.serverhandling;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.minager.core.constant.ResultCode;
import org.minager.core.entities.business.SystemResult;
import org.minager.core.services.business.SystemService;
import org.minager.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ServerHandlingService {
	
	@Autowired
	private SystemService systemService;
	
	@Value("${minecraft.server.path}")
	private String minecraftServerPath;
	
	@Value("${minecraft.server.shell.name}")
	private String minecraftServerShellName;
	
	private String buildMinecraftServerShellPath() {
		return StringUtils.concat(minecraftServerPath,
				minecraftServerPath.charAt(minecraftServerPath.length() - 1) == '/' ? "" : '/',
				minecraftServerShellName);
	}
	
	public int getStatus() {
		final SystemResult shellResult = systemService.executeCommand(buildMinecraftServerShellPath(), "api_status");
		return Integer.parseInt(shellResult.getStdOut());
	}
	
	private void startOrStopServer(final HttpServletResponse pResponse, final String pAction) throws IOException {
		final SystemResult shellResult = systemService.executeCommand(buildMinecraftServerShellPath(), pAction);
		
		if(shellResult.getResultCode() == ResultCode.FAILED.val()) {
			pResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
		} else if(shellResult.getResultCode() == ResultCode.STATE_UNCHANGED.val()) {
			pResponse.sendError(HttpServletResponse.SC_CONFLICT);
		} // else -> SUCCESS, so code 200
	}
	
	public void startServer(final HttpServletResponse pResponse) throws IOException {
		startOrStopServer(pResponse, "api_start");
	}
	
	public void stopServer(final HttpServletResponse pResponse) throws IOException {
		startOrStopServer(pResponse, "api_stop");
	}
	
	public void restartServer(final HttpServletResponse pResponse) throws IOException {
		startOrStopServer(pResponse, "api_restart");
	}
}
