package com.mason.server.controller.json;

import java.util.ArrayList;

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.UmlElementContainerDAO;
import com.mason.server.dao.jdo.UmlElementDAO;
import com.mason.server.dao.jdo.UmlRelationshipDAO;
import com.mason.server.dao.jdo.ViewDAO;
import com.mason.server.model.UmlElementContainer;
import com.mason.server.model.UmlModelData;
import com.mason.server.model.UmlRelationship;
import com.mason.server.model.View;

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

	private static ViewDAO viewDAO = new ViewDAO();
	private static UmlElementDAO elementDAO = new UmlElementDAO();
	private static UmlRelationshipDAO relationshipDAO = new UmlRelationshipDAO();
	private static UmlElementContainerDAO elementContainerDAO = new UmlElementContainerDAO();

	@RequestMapping(value = "data/complete", method = RequestMethod.GET)
	public @ResponseBody UmlModelData getComplete(@PathVariable String slug) {
		
		UmlModelData data = new UmlModelData();
		
		data.views = viewDAO.getAllByModelId(KeyFactory.stringToKey(slug).getId());
		data.elements = elementDAO.getAllByModelId(KeyFactory.stringToKey(slug).getId());
		
		if (data.views.size() > 0) {
			data.elementContainers = new ArrayList<UmlElementContainer>();
			data.relationships = new ArrayList<UmlRelationship>();
		}
		
		for (View v : data.views ) {
			data.elementContainers.addAll(elementContainerDAO.getAllByViewId(v.getId()));
			data.relationships.addAll(relationshipDAO.getAllByViewId(v.getId()));
		}
		
		return data;
	}

	@RequestMapping(value = "data/all", method = RequestMethod.GET)
	public @ResponseBody UmlModelData getAll(@PathVariable String slug) {
		
		UmlModelData data = new UmlModelData();
		
		data.views = viewDAO.getAllByModelId(KeyFactory.stringToKey(slug).getId());
		data.elements = elementDAO.getAllByModelId(KeyFactory.stringToKey(slug).getId());

		return data;
	}

}
