package controllers;

import java.io.File;

import controllers.eSecurePlay1.Auth.Check;
import core.services.ApiService.AuthorizedHttpVerb;
import core.services.MediaService;
import models.Test.TestType;
import models.User.Authorizations;
import play.Logger;
import play.mvc.Util;
import utils.StringUtil;

@Check({ Authorizations.TEST_MANAGEMENT, Authorizations.MEDIA_MANAGEMENT })
public class MediaController extends ApiLoggedController {

	private static MediaService mediaService = MediaService.instance();

	public static void testingtoolMedia(String mediaId, File file, String mediaType, String mediaName, String mediaAuthor,
			String mediaDate, String mediaTestId) {
		media(mediaId, file, mediaType, mediaName, mediaAuthor, mediaDate, mediaTestId, TestType.TESTINGTOOL.name());
	}
	
	public static void atlasMedia(String mediaId, File file, String mediaType, String mediaName, String mediaAuthor,
			String mediaDate, String mediaTestId) {
		media(mediaId, file, mediaType, mediaName, mediaAuthor, mediaDate, mediaTestId, TestType.ATLAS.name());
	}
	
	@Util
	public static void media(String mediaId, File file, String mediaType, String mediaName, String mediaAuthor,
			String mediaDate, String mediaTestId, String tt) {
		String jsonResponse = "";
		try {
			addOptions(AuthorizedHttpVerb.POST, AuthorizedHttpVerb.OPTIONS, AuthorizedHttpVerb.GET,
					AuthorizedHttpVerb.DELETE);
			if (isGet()) {
				request.format = "json";
				if (StringUtil.isNil(mediaId)) {
					jsonResponse = mediaService.mediaList(mediaType, mediaName, mediaAuthor, mediaDate, mediaTestId, tt);
				} else {
					jsonResponse = apiService.buildGenericErrorResponse();
				}
			} else if (isPost()) {
				if (StringUtil.isNil(mediaId)) {
					System.out.println("Creating new media " + tt);
					jsonResponse = mediaService.mediaNew(file, tt, mediaTestId);
				} else {
					jsonResponse = apiService.buildGenericErrorResponse();
				}
			} else if (isDelete()) {
				jsonResponse = mediaService.deleteMedia(mediaId);
			} else if (isOptions()) {
				// continue
			} else {
				jsonResponse = apiService.buildHttpVerbNotAllowedResponse();
			}
		} catch (Throwable thr) {
			Logger.error(thr, "Error...");
			jsonResponse = apiService.buildGenericErrorResponse();
		}

		renderJSON(jsonResponse);
	}

	public static void retrieve(String repositoryId, boolean thumb, String thumbId) {
		if (!StringUtil.isNil(repositoryId)) {
			mediaService.retrieveFromRepository(repositoryId, thumb);
		} else {
			mediaService.retrieveThumb(thumbId);
		}
		renderJSON(apiService.buildGenericErrorResponse());
	}
}