package com.mason.server.controller.json;

import java.security.Principal;
import java.util.Hashtable;

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

@RequestMapping("/json/access/")
public class ProjectAccessControllerJson {
	
	Hashtable<String, String> access = new Hashtable<String, String>();
	private static LogDAO logDAO = new LogDAO();

	@RequestMapping(value = "element/{slug}", method = RequestMethod.GET)
	public @ResponseBody int checkOutElement(Principal principal, @PathVariable String slug) {
		
		if (principal == null) {
			
		} else {
			System.out.println("Request Access to Element by " + principal.getName());
		}
		
		if (principal == null || access.containsKey(slug) ) {
			return 0;
		} else {
			access.put(slug, principal.getName());
		}

		logDAO.add(new Log(KeyFactory.stringToKey(slug).getId(), UmlElement.class.getSimpleName(),
				Log.Action.CHECKOUT));
		return 1;
	}

	@RequestMapping(value = "relationship/{slug}", method = RequestMethod.GET)
	public @ResponseBody int checkOutRelationship(Principal principal, @PathVariable String slug) {
		
		if (principal == null || access.containsKey(slug) ) {
			return 0;
		} else {
			access.put(slug, principal.getName());
		}
		logDAO.add(new Log(KeyFactory.stringToKey(slug).getId(), UmlRelationship.class.getSimpleName(),
				Log.Action.CHECKOUT));
		return 1;
	}

	@RequestMapping(value = "checkIn/{slug}", method = RequestMethod.GET)
	public void checkIn( @PathVariable String slug) {
		if (access.containsKey(slug)) {
			access.remove(slug);
			logDAO.add(new Log(KeyFactory.stringToKey(slug).getId(), KeyFactory.stringToKey(slug).getKind(),
					Log.Action.CHECKIN));
		}
	}

}
