package com.workfusion.odf.impl.processor;

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

import groovy.lang.Binding;
import org.json.JSONObject;

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;

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

    public static final String OCR_JSON_CONTEXT_NAME = "ocr_json";
    public 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(DocumentAttr.OCRED, true);
        return newDoc;
    }

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

    private String getToodOcrDocLink() {
        String ocrJson = BindingUtils.getPropertyValue(binding, OCR_JSON_CONTEXT_NAME);
        JSONObject ocr = new JSONObject(ocrJson);
        return ocr.getJSONObject("xmlForCorrectedImage").getString("ocr_tood_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_raw_processed_document_url");
        } else if (result.has("xmlForCorrectedImage")) {
            return result.getJSONObject("xmlForCorrectedImage").getString("ocr_raw_processed_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");
        }
    }

}
