package com.k_int.ca.action;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.k_int.aggregator.harvest.datamodel.HarvestSpanEnum;
import com.k_int.aggregator.harvest.dto.HarvestInstructionDTO;
import com.k_int.aggregator.harvest.service.HarvestInstructionUpdateException;
import com.k_int.aggregator.harvest.service.OAIHarvestService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class NewOrEditHarvestInstructionAction extends ActionSupport implements
		ServletRequestAware {
	private static final long serialVersionUID = 1L;
	private HarvestInstructionDTO instruction = null;
	private long instructionId;
	private boolean deleteInstruction;
	private OAIHarvestService service;
	protected HttpServletRequest request;

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

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setOaiService(OAIHarvestService service) {
		this.service = service;
	}

	public String execute() throws Exception {
		log.debug("New or edit Harvest Instruction action with request.method "
				+ request.getMethod());
		String result = Action.INPUT;

		// Clear all old errors
		this.clearErrorsAndMessages();
		
		Principal principal = request.getUserPrincipal();
		// User must be authenticated and must be in admin role
		if ((principal != null) && (request.isUserInRole("SYSTEM.admin"))) {
			
			if (instructionId > 0l) {
				if (instruction == null) {
					
					if (deleteInstruction) {	
						log.debug("removing HDO instruction " + instructionId);
						service.deleteHarvestInstructionHDO(instructionId);
						result = Action.SUCCESS;
					}
					else{
						instruction = service.getHarvestInstruction(instructionId);
						log.debug("Have set the service to be non-null as the instruction id is greater than 0l and its currently null");
					}
				}
			} else if (request.getMethod().equals("GET")) {
				// Getting the information about the instruction to edit
				instruction = null;
				log.debug("Have set the instruction to be null as the instruction id is 0");
			}

			// Are we wanting to store changes?
			if (request.getMethod().equals("POST")) {
				// Store changes
				try {
					log.debug("Saving changes");
					service.saveOrUpdateharvestInstruction(instruction);
					result = Action.SUCCESS;
				} catch (HarvestInstructionUpdateException he) {
					log.debug("Exception thrown when updating instruction with id "
							+ instructionId);
					// he.printStackTrace();
					this.addFieldError("instruction.providerCode",
							he.getMessage());
					result = Action.ERROR;
				}
			}
		} else {
			addActionError("You do not have permission for this action.");
			result = Action.ERROR;
		}
		return result;
	}

	public void setInstructionId(String instructionId) {
		if (instructionId != null && !"".equals(instructionId))
			try {
				this.instructionId = Long.parseLong(instructionId);
				log.debug("instruction id set in the new or edit instruction action to "
						+ instructionId);
			} catch (Exception e) {
			}
	}

	public HarvestInstructionDTO getInstruction() {

		if (instruction == null) {
			instruction = new HarvestInstructionDTO();
			instruction.setUri("");
			instruction.setMetadataPrefix("pnds_dc");
			instruction.setProviderCode("");
			instruction.setInterval(7);
			instruction.setMaxRetries(3);
			instruction.setRetryIncrement(5);
			instruction.setUseDates(true);
			instruction.setCharset("UTF-8");
			instruction.setSpan(HarvestSpanEnum.ALL);
			instruction.setParentCollectionName("");
			instruction.setUploadUserName("OAIService");
			instruction.setDefaultNamespace("");
			instruction.setLimitAttribute("limit");
			instruction.setOffsetAttribute("offset");
			instruction.setFetchSize(new Long(10));
			instruction.setHarvestType("OAI");
		}
		return instruction;
	}

	public void setDeleteInstruction(String deleteInstruction) {
		this.deleteInstruction = deleteInstruction.equals("true");
	}

	public void setInstruction(HarvestInstructionDTO instruction) {
		log.debug("setInstruction called in NewOrEditHarvestInstruction");
		this.instruction = instruction;
	}

}
