
const IDWriterTargetName1 = 'invox-ckeditor-v4';
let invoxCKEditor = undefined;

window.addEventListener('load', function (event) {
    InitPageInformation(CKEDITOR4_SINGLE_EDITOR_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;

    invoxCKEditor = new INVOXCKEditor(IDWriterTargetName1, INVOX);
    invoxCKEditor.setExceptionHandler((e) => {
        if (e && e.message) {
            ShowMessage(INVOX.MessageType.ERROR, e.message);
        } else {
            ShowMessage(INVOX.MessageType.ERROR, "Unknown error");
        }
    });
    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);
            }
        }
        
        invoxCKEditor.Login(credentials, connectionConfig)
        .catch(e => {
            e && ShowMessage(INVOX.MessageType.ERROR, e);
            ShowLicenseOrAgentInstructions();
            reject(e);
        });
    })
}

function Logout() {
    invoxCKEditor.Logout();
}

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