
const IDWriterTargetName1 = 'invox-textarea-1';
const IDWriterTargetName2 = 'invox-textarea-2';
let invoxbar = undefined;

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

    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 EventHandler() {
    document.addEventListener(INVOX.eventTypeReport.LOGIN_ERROR, e => {
        ShowMessage(INVOX.MessageType.ERROR, e.detail);
    });
    document.addEventListener(INVOX.eventTypeReport.LOGIN_SUCCESS, e => {
        const editorInstance =  document.getElementById(IDWriterTargetName1)
        ChangeFocusToTextArea(editorInstance);
    });
    document.addEventListener(INVOX.eventTypeReport.NOT_CUSTOMIZED_COMPONENTS, e => {
        ShowMessage(INVOX.MessageType.WARNING, e.detail);
    });
}