
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'
});
class CustomContextMenu extends PDFViewCtrl.viewerui.IContextMenu {
    constructor(widgetAnnotComponent) {
        super();
        this.isVisible = false;
        this.hideOnClickOutside = false;
        this.element = document.createElement('div');
        this.element.className = 'custom-context-menu';
        this.element.innerHTML = `
            <div class="item" action="properties">Properties</div>
            <div class="item" action="delete">Delete</div>
        `;
        this.widgetAnnotComponent = widgetAnnotComponent;
        this.element.addEventListener('click', e => {
            const action = e.target.getAttribute('action');
            if (action == 'properties') {
                // show properties
                pdfui.getStateHandlerManager().then(shm => {
                    shm.switchTo(PDFViewCtrl.STATE_HANDLER_NAMES.STATE_HANDLER_SELECT_ANNOTATION)
                    pdfui.activateElement(widgetAnnotComponent);
                    pdfui.getComponentByName('fv--form-designer-widget-properties-dialog').then(component => {
                        component.show();
                    })
                });
            } else if (action == 'delete') {
                const annot = this.widgetAnnotComponent.annot;
                const page = annot.page;
                pdfui.getFormFillerService().then(service => {
                    service.removeFocus().then(() => {
                        // wait for the action to be completed before removing the annotation
                        setTimeout(() => {
                            page.removeAnnotByObjectNumber(annot.getObjectNumber());
                        }, 300);
                    });
                });
            }
        });
        this.element.addEventListener('contextmenu', e => {
            e.preventDefault();
        });
        this.destroyController = new AbortController();
        document.addEventListener('mouseup', (e) => {
            if(!this.hideOnClickOutside) {
                return;
            }
            if(this.element.contains(e.target) && e.button !== 0) {
                return;
            }
            setTimeout(() => {
                this.hide();
            });
        }, { signal: this.destroyController.signal });
        
    }
    hide() {
        this.element.remove();
        this.isVisible = false;
    }
    showAt(x, y) {
        super.showAt(x, y);
        document.body.append(this.element);
        this.element.style.left = x + 'px';
        this.element.style.top = y + 'px';
        this.isVisible = true;
        this.hideOnClickOutside = false;
        setTimeout(() => {
            this.hideOnClickOutside = true;
        })
    }
    disable() {
        super.disable();
        this.element.classList.add('disabled');
    }
    enable() {
        super.enable();
        this.element.classList.remove('disabled');
    }
    destroy() {
        super.destroy();
        this.destroyController.abort();
        this.element.remove();
    }
}
pdfui.getPDFViewer().then(pdfViewer => {
    pdfViewer.getAnnotManager().registerMatchRule(function(annot, AnnotClass) {
        if(annot.getType() === 'widget') {
            const field = annot.getField();
            if(field.getType() === PDF.form.FieldType.Sign) {
                return;
            }
            return class CustomWidgetAnnot extends AnnotClass {
                async createFillerModeContextMenu() {
                    return new CustomContextMenu(this);
                }
            }
        }
    });
})
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();
    });
});

pdfui.openPDFByHttpRangeRequest({
    range: {
        url: '../../../../docs/FoxitPDFSDKforWeb_DemoGuide.pdf',
    }
}, { fileName: 'FoxitPDFSDKforWeb_DemoGuide.pdf' });

//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);
};