package com.workfusion.odf.core;

import java.util.List;
import java.util.Map;

import groovy.lang.Binding;

import com.workfusion.odf.impl.converter.html2pdf.PdfReportGenerator;
import com.workfusion.odf.impl.converter.html2pdf.RpaPdfReportGenerator;
import com.workfusion.odf.impl.processor.TransactionImporter;
import com.workfusion.odf.service.DeleteTransactionService;
import com.workfusion.odf.service.DeleteTransactionServiceImpl;
import com.workfusion.odf.api.domain.Transaction;
import com.workfusion.odf.service.TransactionService;
import com.workfusion.odf.service.serialization.BusinessProcessFormats;

/**
 * Core Intake class, providing entry point for object initialization.
 */
public final class Intake extends App {
    private Map<String, String> params;

    Intake(Binding context, Map<String, String> params, List<Module> additionalModules, List<Module> overrideModules, Object injectContext) {
        super(context, additionalModules, overrideModules, injectContext);
        this.params = params;
    }

    public static IntakeBuilder init(final Binding binding) {
        return new IntakeBuilder(binding);
    }

    public String exportTransactionAsJson(final String transactionId) {
        TransactionService transactionService = getInstance(TransactionService.class);
        Transaction transaction = transactionService.byId(transactionId);
        return (transaction != null) ? BusinessProcessFormats.toJson(transaction) : "{}";
    }

    public Transaction importTransactionFromJson(final String transactionId, final String json) {
        TransactionImporter transactionImporter = getInstance(TransactionImporter.class);
        Transaction parsedTransaction = BusinessProcessFormats.fromJson(json);
        Transaction importedTransaction = transactionImporter.transform(parsedTransaction);

        TransactionService transactionService = getInstance(TransactionService.class);
        transactionService.update(importedTransaction);
        return importedTransaction;
    }

    public String generatePdfReport(final String webLink) {
        final PdfReportGenerator pdfReportGenerator = getInstance(RpaPdfReportGenerator.class);
        return pdfReportGenerator.generatePdfAndUploadToS3(webLink);
    }

    public String generatePdfReport(final String webLink, final String s3Bucket, final String s3Folder) {
        final PdfReportGenerator pdfReportGenerator = getInstance(RpaPdfReportGenerator.class);
        return pdfReportGenerator.generatePdfAndUploadToS3(webLink, s3Bucket, s3Folder);
    }

    /**
     * Deletes transaction using requested processor and saves it.
     *
     * @param transactionId ID of the transaction to be deleted.
     */
    public final void deleteTransaction(final String transactionId) {
        DeleteTransactionService deleteTransactionService = getInstance(DeleteTransactionServiceImpl.class);
        deleteTransactionService.deleteTransaction(transactionId);
    }
}
