package com.workfusion.odf.impl.processor;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.Map;

import com.workfusion.odf.api.domain.Document;
import com.workfusion.odf.api.domain.DocumentAttr;
import com.workfusion.odf.processor.DocumentProcessor;
import com.workfusion.rpa.core.BindingUtils;
import groovy.lang.Binding;
import org.json.JSONObject;

/**
 * Replaces original document with OCR'ed version.
 */
public class DocumentOcrLinkProcessor extends DocumentProcessor {

    public static final String META_INFO_JSON = "meta_info_json";

    static final String OCR_JSON_CONTEXT_NAME = "ocr_json";
    static final String OCR_TYPE_CONTEXT_NAME = "ocr_type";

    @Inject
    public DocumentOcrLinkProcessor(Binding binding, @Named("botConfigParams") Map<String, String> params) {
        super(binding, params);
    }

    @Override
    protected Document processDocument(Document document) {
        Document newDoc = document.createChildDocument();
        newDoc.setId(document.getId());
        newDoc.setTextLink(getOcrDocLink());
        newDoc.putAttribute(OCR_JSON_CONTEXT_NAME, BindingUtils.getPropertyValue(binding, OCR_JSON_CONTEXT_NAME));
        newDoc.putAttribute(DocumentAttr.OCRED, true);

        if (params.containsKey(META_INFO_JSON)) {
            newDoc.putAttribute(META_INFO_JSON, params.get(META_INFO_JSON));
        }

        return newDoc;
    }

    private String getOcrDocLink() {
        String ocrType = BindingUtils.getPropertyValue(binding, OCR_TYPE_CONTEXT_NAME);
        if ("tod".equals(ocrType)) {
            return getTodOcrDocLink();
        } else {
            return getStandardOcrDocLink();
        }
    }

    private String getTodOcrDocLink() {
        String ocrJson = BindingUtils.getPropertyValue(binding, OCR_JSON_CONTEXT_NAME);
        JSONObject ocr = new JSONObject(ocrJson);
        return ocr.getJSONObject("xmlForCorrectedImage").getString("ocr_document_url");
    }

    private String getStandardOcrDocLink() {
        String ocrJson = BindingUtils.getPropertyValue(binding, OCR_JSON_CONTEXT_NAME);
        JSONObject result = new JSONObject(ocrJson);
        if (result.has("xml")) {
            return result.getJSONObject("xml").getString("ocr_document_url");
        } else if (result.has("xmlForCorrectedImage")) {
            return result.getJSONObject("xmlForCorrectedImage").getString("ocr_document_url");
        } else if (result.has("html")) {
            return result.getJSONObject("html").getString("ocr_document_url");
        } else if (result.has("txt")) {
            return result.getJSONObject("txt").getString("ocr_document_url");
        } else {
            return result.getJSONObject("pdfSearchable").getString("ocr_document_url");
        }
    }

}
