package uk.ac.reload.editor.upload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;

/**
 *
 * @author Gonzalo
 */
public class BundleRepository {

    private static PostMethod filePost;
    private static PostMethod filePost2;

    public static boolean uploadMetadataBundle(File metadataBundleFile) {
    System.out.println("la ruta del bundledemetadatos "+metadataBundleFile.getAbsolutePath());

//Nuevo repositorio WebService REST

        int status = 0;
        try {
            filePost2 = new PostMethod("http://150.214.2.32:8080/restpository/bundles/");
            Part[] parts = {new FilePart("file", metadataBundleFile)};
            filePost2.setRequestEntity(new MultipartRequestEntity(parts, filePost2.getParams()));

            HttpClient client = new HttpClient();
            status = client.executeMethod(filePost2);


        } catch (Exception ex) {
            System.out.println("Excepcion!!");
            ex.printStackTrace();
            System.out.println("Error al subir el bundle: "
                    + status);

        }


        //repositorio local del colinux
        try {
            filePost = new PostMethod("http://localhost:9090/repository/registry");
            Part[] parts = {new FilePart("fname", metadataBundleFile), new StringPart("action", "add")};
            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
            HttpClient client = new HttpClient();
            int status2 = client.executeMethod(filePost);
            if (status2 == HttpStatus.SC_OK) {
                return true;
            } else {
                return false;
            }
        } catch (HttpException ex) {
           // ex.printStackTrace();
            return false;
        } catch (FileNotFoundException ex) {
          //  ex.printStackTrace();
            return false;
        } catch (IOException ex) {
           // ex.printStackTrace();
            return false;
        } finally {
            if (filePost != null) {
                System.out.println("Liberamos la conexión del filePost");
                filePost.releaseConnection();
            } else {
                System.out.println("filePost era null");
            }
        }
    }
}
