const customModule = UIExtension.modular.module('custom', []);

class WidgetPropertiesAnchorComponent extends UIExtension.SeniorComponentFactory.createSuperClass({
    template: `<span></span>`
}) {
    static getName() {
        return 'widget-properties-anchor'
    }
    show() {
        // Display the widget properties component here
        const root = this.getRoot();
        root.querySelector('@custom:widget-properties-sidebar-panel').active();
    }
}

class WidgetPropertiesSidebarPanelComponent extends UIExtension.SeniorComponentFactory.createSuperClass({
    template: document.getElementById('form-properties-editor-template').innerHTML
}) {
    static getName() {
        return 'widget-properties-sidebar-panel'
    }
    widgetLocked = false;
}

class CustomWidgetBorderColorEditorComponent extends UIExtension.SeniorComponentFactory.createSuperClass({
    template: `<color-picker-button 
        @on.change="$component.onUserChangedColor($args[0])"
        @form-designer-v2:form-property="$component.property"
    ></color-picker-button>`
}) {
    static getName() {
        return 'custom-widget-border-color-editor'
    }
    async mounted() {
        super.mounted();
        const addon = await this.getPDFUI().getAddonInstance('FormDesigner');
        const propertiesService = addon.getPDFFormPropertiesService();
        this.property = propertiesService.getWidgetBorderColor();
        this.property.ownsTo(this);
        this.onPropertyChange(this.property);
        this.property.onChange(() => {
            this.onPropertyChange(this.property);
            this.digest();
        })
    }
    async onUserChangedColor(color) {
        const addon = await this.getPDFUI().getAddonInstance('FormDesigner');
        const propertiesService = addon.getPDFFormPropertiesService();
        const widgets = await propertiesService.getSelectedWidgets()
        await widgets.reduce(async (lastPromise, widget) => {
            await lastPromise;
            if(color === 0) {
                return widget.setMKBorderColor(undefined);
            } else {
                const colorNum = parseInt(color.replace('#', ''), 16);
                return widget.setMKBorderColor(colorNum);
            }
        }, Promise.resolve())
    }
    onPropertyChange(property) {
        if(!property.hasValue || property.value === undefined) {
            this.setValue(undefined);
        } else {
            const value = '#' + property.value.toString(16).padStart(6, '0');
            this.setValue(value);
        }
    }
}
customModule.registerComponent(CustomWidgetBorderColorEditorComponent);
customModule.registerComponent(WidgetPropertiesAnchorComponent);
customModule.registerComponent(WidgetPropertiesSidebarPanelComponent);

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.extend({
        getDefaultFragments() {
            if (UIExtension.PDFViewCtrl.DeviceInfo.isMobile) {
                return [];
            }
            return [{
                target: 'fv--form-designer-widget-properties-dialog',
                action: UIExtension.UIConsts.FRAGMENT_ACTION.REPLACE,
                template: `<custom:widget-properties-anchor name="fv--form-designer-widget-properties-dialog"></custom:widget-properties-anchor>`
            }, {
                target: 'sidebar',
                config: {
                    attrs: {
                        width: '620'
                    }
                }
            }, {
                target: 'sidebar',
                action: UIExtension.UIConsts.FRAGMENT_ACTION.APPEND,
                template: `<custom:widget-properties-sidebar-panel></custom:widget-properties-sidebar-panel>`
            }];
        }
    }),
    addons: UIExtension.PDFViewCtrl.DeviceInfo.isMobile ?
    '../../../../lib/uix-addons/allInOne.mobile.js':
    '../../../../lib/uix-addons/allInOne.js'
});

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

var queryParaPairs = location.search.slice(1).split('&');
var queryParameters = queryParaPairs.reduce(function(map, pair) {
    var kv = pair.split('=');
    map[kv[0]] = decodeURIComponent(kv[1] || '');
    return map;
}, {});

if(queryParameters.file) {
    var reg = /^.+?\/([^\/]+?)(#[^\?#]*)?(\?.*)*$/;
    var result = reg.exec(queryParameters.file);
    var fileName = result? result[1] : document.title + '.pdf';
    pdfui.openPDFByHttpRangeRequest({
        range: {
            url: queryParameters.file,
        }
    }, { fileName: fileName })
} else if (!('file' in queryParameters)) {
    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);
};