
const IDWriterTargetName1 = 'invox-ckeditor-v4';
const IDWriterTargetName2 = 'invox-textarea';
let invoxbar = undefined;
let ckeditor = undefined;

window.addEventListener('load', function (event) {
    InitPageInformation(INVOXBAR_CKEDITOR4_TEXTAREA_PAGE);

    const loginForm = document.querySelector("invox-login-form");
    loginForm.setAttribute("host", CONFIG.remoteDictationServiceHost);
    loginForm.setAttribute("port", CONFIG.remoteDictationServicePort);
    loginForm.setAttribute("use-remote-service", CONFIG.useRemoteDictationService);
    loginForm.setAttribute("username", CONFIG.defaultLogin);
    loginForm.setAttribute("password", CONFIG.defaultPassword);
    loginForm.onClickLogin = Login;
    loginForm.onClickLogout = Logout;

    invoxbar = INVOXMDComponent_Bar.create("invox-bar");
    invoxbar.show();

    CreateCKEditor();

    EventHandler();
});


function Login(credentials, connectionConfig) {
    return new Promise((resolve, reject) => {
        const loginForm = document.querySelector("invox-login-form");
        if (loginForm) {
            if (loginForm.hasAttribute("host")) {
                loginForm.setAttribute("host", connectionConfig.host);
            }
            if (loginForm.hasAttribute("port")) {
                loginForm.setAttribute("port", connectionConfig.port);
            }
        }

        invoxbar.login(credentials, connectionConfig)
        .catch(e => {
            e && ShowMessage(INVOX.MessageType.ERROR, e);
            ShowLicenseOrAgentInstructions();
            reject(e);
        });
    })
}


function Logout() {
    invoxbar.logout();
}


function CreateCKEditor () {
    ckeditor = CKEDITOR.replace(IDWriterTargetName1);
    ckeditor.on("focus", function (e) {
        OnClickCKEditor(e.editor);
    });
}

function EventHandler () {
    document.addEventListener(INVOX.eventTypeReport.LOGIN_ERROR, e => {
        ShowMessage(INVOX.MessageType.ERROR, e.detail);
    });
    document.addEventListener(INVOX.eventTypeReport.LOGIN_SUCCESS, e => {
        ChangeFocusToCkeditor(ckeditor);
    });
    document.addEventListener(INVOX.eventTypeReport.NOT_CUSTOMIZED_COMPONENTS, e => {
        ShowMessage(INVOX.MessageType.WARNING, e.detail);
    });
}