package com.mason.server.controller.json;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.appengine.api.datastore.KeyFactory;
import com.mason.server.dao.jdo.LogDAO;
import com.mason.server.dao.jdo.UmlElementDAO;
import com.mason.server.model.Log;
import com.mason.server.model.UmlElement;
import com.mason.server.model.UmlModelData;

@Controller
@RequestMapping("/json/model/{slug}/")
public class UmlElementControllerJson {

	private static UmlElementDAO elementDAO = new UmlElementDAO();
	private static LogDAO logDAO = new LogDAO();

	@RequestMapping(value = "elements", method = RequestMethod.GET)
	public @ResponseBody UmlModelData getModelElements(@PathVariable String slug) {
		
		UmlModelData data = new UmlModelData();
		
		data.elements = elementDAO.getAllByModelId(KeyFactory.stringToKey(slug).getId());
		
		return data;
	}

	@RequestMapping(value = "element", method = RequestMethod.POST)
	public @ResponseBody Object updateElement(@PathVariable String slug, UmlElement ec) {
		
		UmlElement result = new UmlElement();
		
		ec.setModelIdGenerated(slug);
		
		if (ec.getId() == null ) {
			result = elementDAO.add(ec);
			logDAO.add(new Log(result.getId(), UmlElement.class.getSimpleName(),
					Log.Action.DELETE));
		} else {
			result = elementDAO.update(ec);
			logDAO.add(new Log(result.getId(), UmlElement.class.getSimpleName(),
					Log.Action.DELETE));
		}
		
		return result;
	}

}
