package org.bench4q.web.api;

import java.util.HashMap;
import java.util.Map;

import org.bench4q.share.models.master.OrganizeRecordPortResponseModel;
import org.bench4q.web.masterMessager.RecordPortMessager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.SessionAttributes;

@Controller
@SessionAttributes({ "accessToken" })
public class RecordPortController extends BaseController {

	private RecordPortMessager recordPortMessager;

	public RecordPortMessager getRecordPortMessager() {
		return recordPortMessager;
	}

	@Autowired
	public void setRecordPortMessager(RecordPortMessager recordPortMessager) {
		this.recordPortMessager = recordPortMessager;
	}

	@RequestMapping("addPort")
	@ResponseBody
	public Map<String, Object> addPort(
			@ModelAttribute("accessToken") String accessToken,
			@RequestParam String port) {
		Map<String, Object> map = new HashMap<String, Object>();
		return processRecordPortResponse(map, this.getRecordPortMessager()
				.addPort(accessToken, port));

	}

	@RequestMapping("removePort")
	@ResponseBody
	public Map<String, Object> deletePort(
			@ModelAttribute("accessToken") String accessToken,
			@RequestParam String port) {
		Map<String, Object> map = new HashMap<String, Object>();
		return processRecordPortResponse(map, this.getRecordPortMessager()
				.deletePort(accessToken, port));
	}

	@RequestMapping("loadPorts")
	@ResponseBody
	public Map<String, Object> loadPorts(
			@ModelAttribute("accessToken") String accessToken) {
		Map<String, Object> map = new HashMap<String, Object>();
		OrganizeRecordPortResponseModel organizeRecordPortResponseModel = this
				.getRecordPortMessager().loadPorts(accessToken);
		if (organizeRecordPortResponseModel.isSuccess()) {
			map = success(map);
			map.put("ports", organizeRecordPortResponseModel.getPortModels());
			return map;
		} else {
			return fail(map,
					organizeRecordPortResponseModel.getFailCauseString());
		}

	}

	private Map<String, Object> processRecordPortResponse(
			Map<String, Object> map,
			OrganizeRecordPortResponseModel organizeRecordPortResponseModel) {
		if (organizeRecordPortResponseModel.isSuccess()) {
			return success(map);
		} else {
			return fail(map,
					organizeRecordPortResponseModel.getFailCauseString());
		}
	}
}
