/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.arrebol.taxiservicios.controller.predio;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.arrebol.taxiservicios.controller.catalog.LocationController;
import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.predio.Predio;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Root;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Usuario
 */
public class BucketController extends ConnectionManager implements Serializable {

    public void initS3(String accessKey, String secretKey, String region) {
        setCredientials(new BasicAWSCredentials(
                accessKey,
                secretKey
        ));

        setS3Client(AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(getCredientials()))
                .withRegion(region)
                .build());

    }

    public File utilizarBucket(String accessKey, String secretKey, String region, String bucket, Predio predio, Integer validacionAccion, File documentoSubir, String nombreDocumento) {
        AWSCredentials credentials = new BasicAWSCredentials(
                accessKey,
                secretKey
        );

        AmazonS3 s3Client = AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(region)
                .build();

        if (!s3Client.doesBucketExistV2(bucket)) {

            return null;
        }
        if (validacionAccion == 1) {
            S3Object s3object = s3Client.getObject(bucket, nombreDocumento);
            S3ObjectInputStream inputStream = s3object.getObjectContent();
            String fileArchvioPath = "documento.key";
            File outputFile = new File(fileArchvioPath);

            try ( OutputStream outputStream = new FileOutputStream(outputFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                // Cerrar el outputStream para asegurar que los datos se guarden correctamente
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return outputFile;
        } else {
            s3Client.putObject(new PutObjectRequest(bucket, predio.getId() + "-" + documentoSubir.getName(), documentoSubir));
            return null;
        }
    }
    
    public File saveLogoBucket(String accessKey, String secretKey, String region, String bucket, Location location, Integer validacionAccion, File documentoSubir, String nombreDocumento) {
        AWSCredentials credentials = new BasicAWSCredentials(
                accessKey,
                secretKey
        );

        AmazonS3 s3Client = AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(region)
                .build();

        if (!s3Client.doesBucketExistV2(bucket)) {

            return null;
        }
        if (validacionAccion == 1) {
            S3Object s3object = s3Client.getObject(bucket, nombreDocumento);
            S3ObjectInputStream inputStream = s3object.getObjectContent();
            String fileArchvioPath = "documento.key";
            File outputFile = new File(fileArchvioPath);

            try ( OutputStream outputStream = new FileOutputStream(outputFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                // Cerrar el outputStream para asegurar que los datos se guarden correctamente
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return outputFile;
        } else {
            s3Client.putObject(new PutObjectRequest(bucket, location.getId() + "-" + documentoSubir.getName(), documentoSubir));
            return null;
        }
    }

    private static final long serialVersionUID = 1020525241432403643L;

    private AWSCredentials credientials;
    private AmazonS3 s3Client;

    final Logger logger = LogManager.getLogger(LocationController.class);

    public BucketController() {
    }

    public AWSCredentials getCredientials() {
        return credientials;
    }

    public void setCredientials(AWSCredentials credientials) {
        this.credientials = credientials;
    }

    public AmazonS3 getS3Client() {
        return s3Client;
    }

    public void setS3Client(AmazonS3 s3Client) {
        this.s3Client = s3Client;
    }

}
