package com.bytesw.bytebot.service;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Log4j2
public class BucketService {

    @Value("${application.bucket.tenant}")
    private String tenant;

    @Value("${application.bucket.region}")
    private String region;

    @Value("${application.bucket.fileBucket}")
    private String fileDir;

    @Value("${application.bucket.modelBucket}")
    private String modelDir;

    @Value("${application.bucket.version}")
    private String version;

    @Value("${application.bucket.parameter}")
    private String parameter;

    @Autowired
    private QuestionFileRepository questionFileRepository;

    @Autowired
    private BusinessParameterService businessParameterService;

    private AmazonS3 getS3Client() {
        return AmazonS3ClientBuilder.standard()
                .withRegion(region)
                .build();
    }

    public boolean generate(byte[] file, FileValidationResponse response) {
        String bucketName  = businessParameterService.getBusinessParameterForKey(parameter);
        if (bucketName == null) {
            response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
            throw new NotFoundException();
        }

        boolean result = false;
        File mainFile = new File(response.getFileName());
        try {
            FileOutputStream stream = new FileOutputStream(mainFile);
            stream.write(file);
            String newFile = String.format("%s/%s/%s/%s/%s",tenant, response.getUuid(), version, fileDir, mainFile.getName());
            PutObjectRequest request = new PutObjectRequest(bucketName, newFile, mainFile);
            AmazonS3 amazonS3 = getS3Client();
            amazonS3.putObject(request);
            String modelFile = String.format("%s/%s/%s/%s",tenant, response.getUuid(), version, modelDir);
            createFolder(bucketName, modelFile, amazonS3);
            mainFile.delete();
            result = true;
        } catch (Exception e) {
            log.error("Error al cargar archivo");
        }
        return result;
    }

    public static void createFolder(String bucketName, String folderName, AmazonS3 client) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(0);
        InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
                folderName+"/", emptyContent, metadata);
        client.putObject(putObjectRequest);
    }

    public void delete(String uuid) {
        String bucketName = businessParameterService.getBusinessParameterForKey(parameter);
        if (bucketName == null) {
            throw new NotFoundException();
        }
        try {
            AmazonS3 s3Client = getS3Client();
            Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
            if (!questionFile.isPresent()) {
                throw new NotFoundException();
            }
            String keyName = String.format("%s/%s/%s/%s/%s",tenant, uuid, version, fileDir, questionFile.get().getName());
            s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
            keyName = String.format("%s/%s/%s/%s/",tenant, uuid, version, modelDir);
            s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
    }

}
