package eu.cloudopting.web.rest;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.jcr.Node;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.commons.JcrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RestController;

import eu.cloudopting.security.AuthoritiesConstants;
import eu.cloudopting.store.StoreService;

@RestController
@RequestMapping("/api")
public class JcrImageResource {

	private final Logger log = LoggerFactory.getLogger(JcrImageResource.class);

	@Inject
	private StoreService storeService;
	
	@Inject 
	private Repository repo;
		
	@Inject
	private Session session;
    
    /**
     * JackRabbit Repository URL
     */
    @Value("${spring.jcr.repo_http}")
	private String jrHttp;
    
    private String getRelativePathForNode(String jcrPath){
    	String result = null;
    	String jrRepositoryBase = "http://lab1.cloudopting.org:8083/repository/default/";
		StoreService ss = this.getStoreService();
		if (ss!=null){
			jrRepositoryBase = ss.getJrHttp();
		}else{
			String s = "Store Service NOT injected!";
			if (log!=null){
				log.error(s);
			}else{
				System.out.println(s);
			}
		}
		result = StringUtils.removeStart(jcrPath, jrRepositoryBase); 
		if (!result.startsWith("/")){
			result = "/"+result;
		}
		return result;
    }
	
	@RequestMapping(value = "/jr/img", method = RequestMethod.GET)
	@RolesAllowed(AuthoritiesConstants.ANONYMOUS)
	public final ResponseEntity<InputStreamResource> getJcrImage(@RequestParam("jcrPath") String jcrPath) {
		ResponseEntity<InputStreamResource> result = null;
		String relativePath = this.getRelativePathForNode(jcrPath);
		InputStream is = null;
		try {
			Session s = this.getSession();
			Node n = JcrUtils.getNodeIfExists(relativePath, s);
			is = JcrUtils.readFile(n);
			Node jcrContent = n.getNode("jcr:content");
			String fileName = n.getName();
			long size = jcrContent.getProperty("jcr:data").getBinary().getSize();
			HttpHeaders respHeaders = new HttpHeaders();
			String mType = jcrContent.getProperty("jcr:mimeType").getString();
			respHeaders.setContentType(MediaType.parseMediaType(mType));
			respHeaders.setContentLength(size);
			//respHeaders.setContentDispositionFormData("attachment", fileName);
			InputStreamResource isr = new InputStreamResource(is);
			result = new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
		} catch (RepositoryException e) {
			e.printStackTrace();
			log.error("Repository Exception", e);
			result = new ResponseEntity<InputStreamResource>(new InputStreamResource(is), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
		} finally {
			try {
				if (is!=null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.warn("Repository Exception", e);
			}
		}
	    return result;
	}
	
	public Logger getLog() {
		return log;
	}

	public StoreService getStoreService() {
		return storeService;
	}
	
	public Session getSession() {
		return session;
	}
}
@@ -88,55 +88,8 @@
 m;%0A%0A
-import javax.annotation.security.RolesAllowed;%0A
 impo
@@ -139,37 +139,8 @@
 de;%0A
-import javax.jcr.Repository;%0A
 impo
@@ -898,61 +898,8 @@
 r;%0A%0A
-import eu.cloudopting.security.AuthoritiesConstants;%0A
 impo
@@ -1139,47 +1139,8 @@
 ;%0A%09%0A
-%09@Inject %0A%09private Repository repo;%0A%09%09%0A
 %09@In
@@ -1917,55 +1917,8 @@
 ET)%0A
-%09@RolesAllowed(AuthoritiesConstants.ANONYMOUS)%0A
 %09pub
@@ -2336,42 +2336,8 @@
 %22);%0A
-%09%09%09String fileName = n.getName();%0A
 %09%09%09l
@@ -2630,80 +2630,8 @@
 e);%0A
-%09%09%09//respHeaders.setContentDispositionFormData(%22attachment%22, fileName);%0A
 %09%09%09I
@@ -3189,24 +3189,513 @@
 esult;%0A%09%7D%0A%09%0A
+%09@RequestMapping(value = %22/jr/img%22, method = RequestMethod.DELETE)%0A%09public final Boolean deleteJcrImage(@RequestParam(%22jcrPath%22) String jcrPath) %7B%0A%09%09Boolean result = false;%0A%09%09String relativePath = this.getRelativePathForNode(jcrPath);%0A%09%09try %7B%0A%09%09%09Session s = this.getSession();%0A%09%09%09s.removeItem(relativePath);%0A%09%09%09s.save();%0A%09%09%09result = true;%0A%09%09%7D catch (RepositoryException e) %7B%0A%09%09%09e.printStackTrace();%0A%09%09%09log.error(%22Repository Exception%22, e);%0A%09%09%09result = false;%0A%09%09%7D %0A%09    return result;%0A%09%7D%0A%09%0A
 %09public Logg

Fix for #222