package ve.gob.cnti.gestion.alfresco;

import java.io.ByteArrayInputStream;
import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;



import org.apache.commons.io.FileUtils;




import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import ve.gob.cnti.receiver.utils.PropertiesReader;
import ve.gob.cnti.gestion.alfresco.ICmisController;
import ve.gob.cnti.gestion.alfresco.FileMessage;



/**
 * Loads the images in a local folder into a CMIS repo. Extend CloudExampleBase
 * to load into Alfresco in the cloud. Extend LocalExampleBase to load into a
 * local repo.
 * 
 * @author jpotts
 * 
 */
public class AlfrescoLoadFiles implements ICmisController {
	ve.gob.cnti.receiver.utils.PropertiesReader pr = new PropertiesReader();	
	public String REPOSITORY_URL = pr.getProperty("REPOSITORY_URL");
	
	/**
	 * Uploads all files in a local directory to the CMIS server.
	 * 
	 * @throws IOException
	 */
	public String uploadDocument(File file, String pathFolder,
			String nameFile) {


		String id = "";

		
		byte[] stream=null;
		try {
			stream = FileUtils.readFileToByteArray(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		FileMessage fileMessage=new FileMessage(pathFolder,file.getName(),stream,"application/pdf");
        ClientConfig clientConfig = new DefaultClientConfig();
        
        clientConfig.getFeatures().put(
                JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);

        WebResource webResource = client
                .resource(REPOSITORY_URL+"rest/fileUpload/upload");
     

        ClientResponse response = webResource.accept("application/json")
            .type("application/json").post(ClientResponse.class,fileMessage);
        long value=response.getEntity(long.class);
        if (value== 0) {
            throw new RuntimeException("El archivo no se almaceno en el repositorio");
        }
		id=String.valueOf(value);
		return id;
	}


	public ContentStream getDocument(String documentID) {

	        ClientConfig clientConfig = new DefaultClientConfig();
	        
	        clientConfig.getFeatures().put(
	                JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

	        Client client = Client.create(clientConfig);

	        WebResource webResource = client
	                .resource(REPOSITORY_URL+"rest/fileDownload/download");

	      
	        ClientResponse response = webResource.queryParam("identify", documentID).accept("application/json")
	            .type("application/json").get(ClientResponse.class);

	        if (response.getStatus() != 200) {
	            throw new RuntimeException("Failed : HTTP error code : "
	                    + response.getStatus());
	        }

	        FileMessage output = response.getEntity(FileMessage.class);	        
	        InputStream stream = new ByteArrayInputStream(output.getFileUp()); 
	        ContentStream contentStream=new ContentStream(output.getName(),stream,output.getContenttype(),output.getFileUp().length,BigInteger.valueOf(output.getFileUp().length));
	        return contentStream;
		
	}

	public FileMessage getFileMessage(String documentID) {

        ClientConfig clientConfig = new DefaultClientConfig();
        
        clientConfig.getFeatures().put(
                JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);

        WebResource webResource = client
                .resource(REPOSITORY_URL+"rest/fileDownload/download");

      
        ClientResponse response = webResource.queryParam("identify", documentID).accept("application/json")
            .type("application/json").get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

        FileMessage output = response.getEntity(FileMessage.class);	        
        return output;
	
 }



	public void deletedDocument(String documentID) {


		
		
	    ClientConfig clientConfig = new DefaultClientConfig();
	    
	    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
	
	    Client client = Client.create(clientConfig);
	
	    WebResource webResource = client
	            .resource(REPOSITORY_URL+"rest/fileDelete/delete");
	
	  
	    ClientResponse response = webResource.queryParam("identify", documentID).accept("application/json")
	        .type("application/json").delete(ClientResponse.class);
	
	    if (response.getStatus() != 200) {
	        throw new RuntimeException("Failed : HTTP error code : "
	                + response.getStatus());
	    }
	
	
		
		

	}

}
