package net.waltzstudio.montecarlo.action.api;

import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import net.arnx.jsonic.JSON;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;
import org.seasar.struts.util.ResponseUtil;
import net.waltzstudio.base.framework.util.BaseUtil;
import net.waltzstudio.montecarlo.dto.api.TicketDto;
import net.waltzstudio.montecarlo.form.ApiForm;
import net.waltzstudio.montecarlo.service.ApiService;

/**
 * API Action
 */
public class IndexAction {

	/** API Service */
	@Resource
	protected ApiService apiService;

	/** API Form */
	@Resource
	@ActionForm
	protected ApiForm apiForm;

	@Execute(validator = false)
	public String index() {
		return null;
	}

	@Execute(validator = false)
	public String ticket() {
		Long projectId = null;
		Long labelId = null;
		boolean inbox = false;

		String sProjectId = apiForm.projectId;
		if ("all".equals(sProjectId)) {
			projectId = null;
		} else {
			projectId = BaseUtil.Cast.toLong(sProjectId);
		}
		String sLabelId = apiForm.labelId;
		if ("all".equals(sLabelId)) {
			labelId = null;
			inbox = false;
		} else if ("tray".equals(sLabelId)) {
			labelId = null;
			inbox = true;
		} else {
			labelId = BaseUtil.Cast.toLong(sLabelId);
			inbox = false;
		}

		List<TicketDto> tickets = apiService.getTickets(projectId, labelId, inbox);

		try {
			HttpServletResponse response = ResponseUtil.getResponse();
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.write(JSON.encode(tickets));
			out.flush();
			out.close();
		} catch (Exception e) {
			BaseUtil.sendError(500);
		}

		return null;
	}

}
