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.UmlRelationshipDAO;
import com.mason.server.model.Log;
import com.mason.server.model.UmlRelationship;

@Controller
@RequestMapping("/json/view/{slug}/")
public class UmlRelationControllerJson {

	private static UmlRelationshipDAO relationshipDAO = new UmlRelationshipDAO();
	private static LogDAO logDAO = new LogDAO();

	@RequestMapping(value = "relationship", method = RequestMethod.POST)
	public @ResponseBody
	UmlRelationship updateRelationship(@PathVariable String slug,
			UmlRelationship ur) {

		UmlRelationship result = null;

		ur.setViewIdGenerated(slug);

		if (ur.getId() == null) {
			result = relationshipDAO.add(ur);
			logDAO.add(new Log(result.getId(), UmlRelationship.class.getSimpleName(),
					Log.Action.DELETE));
		} else {
			result = relationshipDAO.update(ur);
			logDAO.add(new Log(result.getId(), UmlRelationship.class.getSimpleName(),
					Log.Action.DELETE));
		}

		return result;
	}

	@RequestMapping(value = "relationship/{relationshipSlug}", method = RequestMethod.DELETE)
	public void deleteRelationship(@PathVariable String slug,
			@PathVariable String relationshipSlug) {
		relationshipDAO.deleteById(KeyFactory.stringToKey(relationshipSlug)
				.getId());

		logDAO.add(new Log(KeyFactory.stringToKey(relationshipSlug).getId(), UmlRelationship.class.getSimpleName(),
				Log.Action.DELETE));
	}

}
