package com.workfusion.odf.impl.processor;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.springframework.http.MediaType;

import com.workfusion.odf.api.domain.Document;
import com.workfusion.odf.impl.converter.excel2html.ToHtmlConverter;
import com.workfusion.odf.processor.DocumentConverter;
import com.workfusion.odf.processor.TransactionProcessor;
import com.workfusion.rpa.core.storage.S3Manager;

public class ExcelToHtmlProcessor extends DocumentConverter implements TransactionProcessor {
    private final static String S3_FOLDER = "excel_converted";
    private final S3Manager s3Manager;
    private Logger logger;
    private ToHtmlConverter htmlConverter;

    @Inject
    public ExcelToHtmlProcessor(S3Manager s3Manager, final Logger logger, ToHtmlConverter htmlConverter) {
        this.s3Manager = s3Manager;
        this.htmlConverter = htmlConverter;
    }

    @Override
    protected Set<Document> convertDocument(final Document excelDoc){//to Document
        final byte[] contentOriginal = s3Manager.getContent(excelDoc.getOriginalDocumentLink());

        final byte[] newFile = htmlConverter.convertToHTML(contentOriginal);
        final String nameForNewFile = generateNameOfNewFile();
        final String htmlLink = s3Manager.uploadFileToS3(newFile, nameForNewFile, MediaType.TEXT_HTML_VALUE);

        final Document htmlDoc = excelDoc.createChildDocument();
        htmlDoc.setTextLink(htmlLink);

        final Set<Document> result = new HashSet<>();
        result.add(htmlDoc);
        return result;
    }

    private String generateNameOfNewFile() {
        return S3_FOLDER + "/" + UUID.randomUUID().toString() + getExtensionOfNewFile();
    }

    private String getExtensionOfNewFile() {
        return ".html";
    }

    @Override
    protected Predicate<Document> getDocumentFilter() {
        return Document::isExcelDocument;
    }
}
