package com.libreecm.input.controllers;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.libreecm.commonAPI.model.objects.Uri;
import com.libreecm.commonAPI.auxiliars.exceptions.NotAccessibleRepositoryException;
import com.libreecm.commonAPI.configuration.ComponentConfig;
import com.libreecm.commonAPI.configuration.Config;
import com.libreecm.commonAPI.model.Repository;
import com.libreecm.input.auxiliars.RepositoryCreator;
import com.libreecm.input.repositoriesImpl.RepositoryImpl;

@RestController
public class RepositoryController extends BaseController {

	/**
	 * Returns a Repository from the FS or DB persistence system
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/repository", method = RequestMethod.GET)
	public @ResponseBody Repository getRepository(@RequestParam(value = "name", required = true) String name) {
		// validateUser();
		RepositoryImpl repository = RepositoryCreator.get().getRepository(name);
		// Testing repository validation
		if (repository.getId().length() == 0 || repository.getTypeId().length() == 0 ||
				// TODO Bug here
				// repository.getAccessible()==false||
				// repository.getActive()==false||
		(repository.getUri()).toString().length() == 0 || repository.getRootFolderId().length() == 0) {
			throw new NotAccessibleRepositoryException(name);
		}

		System.out.println("From input controller getrepository: "+repository);
		return repository;
	}

	/**
	 * <p>Returns a Repository from the FS or DB persistence system updating some
	 * data</p>
	 * 
	 * <p>Deprecated because it's better to get as a GET call</p>
	 * 
	 * @deprecated It's better to call as a GET
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/repository", method = RequestMethod.POST)
	public @ResponseBody RepositoryImpl getRepository(@RequestBody Repository repository) throws IOException {
		// validateUser();
		//System.out.println("form input repository controller, setting repository "+repository.getName()); 
    	RepositoryImpl result = RepositoryCreator.get().getRepository(repository);
		// Testing repository validation
		if (result.getTypeId().length() == 0 || repository.getName().isEmpty() ||
				// TODO Bug here
				// repository.getAccessible()==false||
				// repository.getActive()==false||
		(result.getUri()).toString().length() == 0 || result.getRootFolderId().length() == 0) {
			throw new NotAccessibleRepositoryException(repository.getName());
		}
		return result;

	}
}