package com.theorchard.javaowsassetbulkscript;

import com.theorchard.javaowsassetbulkscript.logic.AWSDetails;
import com.theorchard.javaowsassetbulkscript.logic.AutomaticAssetImporter;
import com.theorchard.javaowsassetbulkscript.logic.LabelExcelLoader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.File;
import java.util.Map;

@SpringBootApplication
public class JavaOwsAssetBulkScriptApplication {

    public static void main(String[] args) throws Exception {
        //args = new String[] {"finetunes-upload-temp", "xxx", "xxx", "finetunes", "eu-central-1", "1096555797649", "src/main/resources/finetunes_to_orchard_labelids.xls"};

        checkSetup();

        if (args.length == 7) {
            try {
                if (args.length < 7) {
                    System.out.println("Usage: bucket publicKey privateKey path region labelId labelId_to_orchardId.xls");
                    return;
                }

                String bucket = args[0];
                String publicKey = System.getenv("FTPUBKEY");
                String privateKey = System.getenv("FTPRIVKEY");
                String path = args[3];
                String region = args[4];
                String labelId = args[5];
                String filePath = args[6];

                Map<String, String> mapping = LabelExcelLoader.loadLabelMapping(new File(filePath));

                if (!mapping.containsKey(labelId)) {
                    throw new Exception("Label ID cannot be mapped to an Orchard Vendor ID");
                }

                AWSDetails awsDetails = new AWSDetails(bucket, publicKey, privateKey, path, region);
                AutomaticAssetImporter importer = new AutomaticAssetImporter();

                String vendorId = mapping.get(labelId);
                importer.transferLabel(awsDetails, labelId, Integer.parseInt(vendorId), false, false);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            SpringApplication.run(JavaOwsAssetBulkScriptApplication.class, args);
        }
    }

    private static void checkSetup() throws Exception {
        String useQA = System.getenv("USEQA");
        String ftPubKey = System.getenv("FTPUBKEY");
        String ftPrivKey = System.getenv("FTPRIVKEY");

        if (useQA == null || ftPrivKey == null || ftPubKey == null) {
            throw new Exception("Env Variables not setup");
        }
    }
}
