import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.ho.yaml.Yaml;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.TransferManager;

public class S3SqlFileReader {
	
	public Map<String,Object> params;
	
	public String sqlUri;
	
	public String bucket;
	
	public String tmpDir = "/mnt/data/tmp/tmp.sql";
	
	private String configFilePath = "/mnt/data/ETL/java/accounting/config/config.yml";
	
	public S3SqlFileReader(String sql, String buck){
		sqlUri = sql;
		bucket = buck;
	}
	
	public void setConfigFilePath(String path){
		configFilePath = path;
	}
	@SuppressWarnings("deprecation")
	public String getSQLFromS3() throws IOException, InterruptedException{
		System.out.println("Getting S3 configurations from: "+configFilePath);
		Map<String,Object> conf = new HashMap<String,Object>();
    	conf = (Map)Yaml.load(new File(configFilePath));
		
		System.out.println("Downloading object: '"+sqlUri+"' from S3 bucket: '"+bucket+"'\n");
		File file = new File(tmpDir);
		if(file.exists()){
			file.delete();
		}
		TransferManager tx = new TransferManager(new BasicAWSCredentials((String)conf.get("accessKey"),(String)conf.get("accessSecret")));
		Download download = tx.download(bucket, sqlUri, file);

		while (download.isDone() == false) {
		    System.out.println(download.getProgress().getPercentTransfered() + "%");
			Thread.sleep(100);
		}
		
		byte[] encoded = Files.readAllBytes(Paths.get(tmpDir));
		file.delete();
		return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
	}
}
