/**
 * The message handler ID.
 * @type {string}
 */
const MESSAGE_HANDLER_NAME = 'helpkit';

/**
 * The message keys.
 * @type {string}
 */
const EVENT_KEY = 'event';
const CONTACT_TYPE_KEY = 'contactType';
const CHAT_SUPPORT_REQUEST_ID_KEY = 'chatSupportRequestID';
const CASE_ID_KEY = 'caseID';

/**
 * The event values.
 * @type {string}
 */
const SUBMIT_END_EVENT = 'submitend';
const ERROR_EVENT = 'error';
const LOAD_ERROR_EVENT = 'loadError';

window.get_help = function(page) {
  var getHelpFlow = page.getChild();
  if (typeof getHelpFlow === 'undefined') {
    return;
  }
  getHelpFlow.getFormFlowStep().getEmbeddedForm().setContactFormCallback(
      function(form) {
        form.setGcmRegistrationId(window.HELPKIT_FCM_REGISTRATION_TOKEN);
        form.listen(SUBMIT_END_EVENT, function() {
          window.webkit.messageHandlers[MESSAGE_HANDLER_NAME].postMessage({
            [EVENT_KEY]: SUBMIT_END_EVENT,
            [CONTACT_TYPE_KEY]: form.getContactType(),
            [CHAT_SUPPORT_REQUEST_ID_KEY]: form.getChatSupportRequestId() || '',
            [CASE_ID_KEY]: form.getCaseId() || ''
          });
        });
        form.listen(ERROR_EVENT, function() {
          window.webkit.messageHandlers[MESSAGE_HANDLER_NAME].postMessage({
            [EVENT_KEY]: ERROR_EVENT,
            [CONTACT_TYPE_KEY]: form.getContactType()
          });
        });
      });
  getHelpFlow.getFormFlowStep().setOnLoadErrorCallback(function() {
    window.webkit.messageHandlers[MESSAGE_HANDLER_NAME].postMessage(
        {[EVENT_KEY]: LOAD_ERROR_EVENT});
  });
};
