
const PDFUI = UIExtension.PDFUI;
const Events = UIExtension.PDFViewCtrl.Events;
const pdfui = new PDFUI({
    viewerOptions: {
        libPath: '../../../../lib',
        jr: {
            readyWorker: readyWorker
        }
        // customs: {
        //     getDocPermissions: function () {
        //         return 0;
        //     }
        // }
    },
    renderTo: '#pdf-ui',
    appearance: UIExtension.appearances.adaptive,
    addons: UIExtension.PDFViewCtrl.DeviceInfo.isMobile ?
    '../../../../lib/uix-addons/allInOne.mobile.js':
    '../../../../lib/uix-addons/allInOne.js'
});

pdfui.getPDFViewer().then(pdfViewer => {
    const service = pdfViewer.getFormFillerService();
    service.appendInteractionEventInterceptor(async (options, next) => {
        const { event, widgetId } = options;
        if(event.type !== 'mouseup') {
            return next();
        }
        const doc = pdfViewer.getCurrentPDFDoc();
        const widget = await doc.query({ type: 'annot', annotId: widgetId });
        if(!widget) {
            return next()
        }
        const field = widget.getField();
        if(field.getType() !== PDF.form.FieldType.Sign) {
            return next();
        }
        const result = window.confirm('Are you sure to sign this document?');
        if (result) {
            await next();
        }
    });
})
pdfui.addUIEventListener('fullscreenchange', function (isFullscreen) {
    if (isFullscreen) {
        document.body.classList.add('fv__pdfui-fullscreen-mode');
    } else {
        document.body.classList.remove('fv__pdfui-fullscreen-mode');
    }
});

function openLoadingLayer() {
    // return pdfui.getRootComponent()
    // .then(function(root) {
    //     return root.getComponentByName('pdf-viewer')
    // }) .then(function(viewerComponent) {
    //     return pdfui.loading(viewerComponent.element);
    // });
    return pdfui.loading();
}
var loadingComponentPromise;
var openFileError = null
var passwordErrorCode = PDFViewCtrl.PDF.constant.Error_Code.password
function startLoading() {
    if(openFileError&&openFileError.error===passwordErrorCode)return
    if (loadingComponentPromise) {
        loadingComponentPromise = loadingComponentPromise
            .then(function (component) {
                component.close();
            })
            .then(openLoadingLayer);
    } else {
        loadingComponentPromise = openLoadingLayer();
    }
}
pdfui.addViewerEventListener(Events.beforeOpenFile, startLoading);
pdfui.addViewerEventListener(Events.openFileSuccess, function () {
    openFileError = null;
    loadingComponentPromise.then(function (component) {
        component.close();
    });
});
pdfui.addViewerEventListener(Events.openFileFailed, function (data) {
    openFileError = data
    if(openFileError&&openFileError.error===passwordErrorCode)return
    loadingComponentPromise.then(function (component) {
        component.close();
    });
});

//signature handlers
var requestData = function(type, url, responseType, body){
    return new Promise(function(res, rej){
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open(type, url);

        xmlHttp.responseType = responseType || 'arraybuffer';
        var formData = new FormData();
        if (body) {
            for (var key in body) {
                if (body[key] instanceof Blob) {
                    formData.append(key, body[key], key);
                } else {
                    formData.append(key, body[key]);
                }
            }
        }
        xmlHttp.onloadend = function(e) {
            var status = xmlHttp.status;
            if ((status >= 200 && status < 300) || status === 304) {
                res(xmlHttp.response);
            }else{
                rej(new Error('Sign server is not available.'));
            }
        };
        
        xmlHttp.send(body ? formData : null);
    });
};

var workflowService = pdfui.getSignatureWorkflowService();
var engineSignatureService = pdfui.getSignatureService();

engineSignatureService.setVerifyHandler(function (signatureField, plainBuffer, signedData){
    return Promise.all([
        signatureField.getFilter(),
        signatureField.getSubfilter(),
        signatureField.getSigner()
    ]).then((params) => {
        var filter = params[0];
        var subfilter = params[1];
        var signer = params[2];
        return requestData('post', location.origin+'/signature/verify', 'text', {
            filter: filter,
            subfilter: subfilter,
            signer: signer,
            plainContent: new Blob([plainBuffer]),
            signedData: new Blob([signedData])
        });
    })
});
workflowService.addSignerInfo({
    filter: 'Adobe.PPKLite',
    subfilter: 'adbe.pkcs7.sha1',
    signer: 'web sdk',
    sign: function(setting, plainContent) {
        return requestData('post', location.origin+'/signature/digest_and_sign', 'arraybuffer', {
            plain: plainContent
        })
    }
});
workflowService.addSignatureAPInfo({
    title: 'Standard Style',
    distinguishName: 'e=foxitsdk@foxitsoftware.cn',
    location: 'FZ',
    reason: 'Test',
    flag: 0x17F,
    showTime: true,
});
// Prevent iPhone from Auto Zoom in Input text fields.
window.onload = function () {
    if(!UIExtension.PDFViewCtrl.DeviceInfo.isIPHONE)return
    var lastTouchEnd = 0;
    document.addEventListener('touchend', function (event) {
    var now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        event.preventDefault();
    }
    lastTouchEnd = now;
    }, false);
};