/*
* These blocks allow to send notifications via openhab
* supports jsscripting
*/

import Blockly from 'blockly'
import { javascriptGenerator } from 'blockly/javascript.js'
import { blockGetCheckedInputType } from './utils.js'

export default function defineOHBlocks_Notifications (f7) {
  Blockly.Blocks['oh_sendNotification'] = {
    init: function () {
      this.appendValueInput('message')
        .appendField('send notification')
      this.appendValueInput('email')
        .appendField('to e-mail address')
      this.setPreviousStatement(true, null)
      this.setNextStatement(true, null)
      this.setInputsInline(false)
      this.setColour(0)
      this.setTooltip('Deprecated: send a notification message to a specific openhab user (requires openHAB Cloud Connector)')
      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#send-notification-to-specific-cloud-email-user')
    }
  }

  javascriptGenerator.forBlock['oh_sendNotification'] = function (block) {
    const email = javascriptGenerator.valueToCode(block, 'email', javascriptGenerator.ORDER_ATOMIC)
    const message = javascriptGenerator.valueToCode(block, 'message', javascriptGenerator.ORDER_ATOMIC)
    return `actions.notificationBuilder(${message}).addUserId(${email}).send();\n`
  }

  Blockly.Blocks['oh_sendBroadcastNotification'] = {
    init: function () {
      this.appendValueInput('message')
        .appendField('send notification')
      this.appendValueInput('icon')
        .appendField('with icon')
      this.appendDummyInput()
        .appendField('as')
        .appendField(new Blockly.FieldDropdown([['info', 'info'], ['warning', 'warn'], ['highly important', 'high']]), 'severity')
        .appendField('to all devices')
      this.setPreviousStatement(true, null)
      this.setNextStatement(true, null)
      this.setInputsInline(false)
      this.setColour(0)
      this.setTooltip('Deprecated: send a notification to all clients. Provide icon name without prefix. (requires openHAB Cloud Connector)')
      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#send-notification-to-all-devices-and-users')
    }
  }

  javascriptGenerator.forBlock['oh_sendBroadcastNotification'] = function (block) {
    const message = javascriptGenerator.valueToCode(block, 'message', javascriptGenerator.ORDER_ATOMIC)
    const icon = javascriptGenerator.valueToCode(block, 'icon', javascriptGenerator.ORDER_ATOMIC)
    const severity = block.getFieldValue('severity')
    return `actions.notificationBuilder(${message}).withIcon(${icon}).withTag('${severity}').send();\n`
  }

  Blockly.Blocks['oh_sendLogNotification'] = {
    init: function () {
      this.appendValueInput('message')
        .appendField('send notification')
      this.appendValueInput('icon')
        .appendField('with icon')
      this.appendDummyInput()
        .appendField('as')
        .appendField(new Blockly.FieldDropdown([['info', 'info'], ['warning', 'warn'], ['highly important', 'high']]), 'severity')
        .appendField('to log only')
      this.setPreviousStatement(true, null)
      this.setNextStatement(true, null)
      this.setInputsInline(false)
      this.setColour(0)
      this.setTooltip('Deprecated: sends a notification to the cloud log only, not to any device (requires openHAB Cloud Connector)')
      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#send-notification-to-log-only')
    }
  }

  javascriptGenerator.forBlock['oh_sendLogNotification'] = function (block) {
    const message = javascriptGenerator.valueToCode(block, 'message', javascriptGenerator.ORDER_ATOMIC)
    const icon = javascriptGenerator.valueToCode(block, 'icon', javascriptGenerator.ORDER_ATOMIC)
    const severity = block.getFieldValue('severity')
    return `actions.notificationBuilder(${message}).logOnly().withIcon(${icon}).withTag('${severity}').send();\n`
  }

  const usersImage = 'data:image/png;base64,[encoded data, 4176 characters]'
  const iconImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAGsElEQVRYha1XXUwb2Rk94x9IMCbZusFN2HQ7OJbNlmzCliKk0iQNUwMx0iZ+SolUKZZWqpOqWipoVIGqqtsKJUFUjlqqSBX0oeUhpCJKhUDWAEWRNjwQXGnZ4Ozay/6lrVdyw2LGA/47fTCwQPDgqP2kK92599zznZl7537fJ5BEIXb58mVdVVVVaW1t7QFRFA9YLBaTyWTSA1hVFEWNxWKJxcVFZXZ2VllYWFgbHBzMFsIr7CXgypUr+1wuV6XL5Xq1pKTkEAATADMAPQACSAFQASQAxAF8kUgk/hkIBCKBQGCpv79fU4imgIGBAZvX6/0egEoAhwG8B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hGI+OjIxMzc3N4ZFHHkE8Hse6jnvVUJfcOk/qKVEUZWs4HP49pbTFcRzt5MmTO5eWlr6urwEA/L59+zxyKYqCVCq1tLi4+NvOzs4DqqreJcvyT4LBYFLTtEuyLJdDoZDXmtcrw7ZtmKbpNTCCILSGw+FfhkKhNwkhDcVicfKdd97ZlkqlUi0tLXc0Oty7775764ZCCBhj4DgOuq5DURTs3bv3jZ6eniP1Xem6ft513f+0bfuKaZo3ABTWT8kQz/NtgiB8V1XVJ0VR3Fl3MDk5+fIHH3zwL4VCAZs2bYIsy544iaJ4i4Su60LXdU9sVFVFoVCApmno6elp37Fjx8ttbW2e5t8uSLcL1O02MzNzYmxs7F+vX7++TCkFIQSUUqiqCtu2oSgKKKXg7rnnHjz33HPebQcAZFn28lkqlSBJErq7u4NNTU0HbNveE41GtyQSiaQgCMH16BRrtdo8gCuTk5N/XFhYGE6lUrplWYhGo6hWq6hUKhBF0btTiqKI48eP438BrpLLQlK5PgEAAAAASUVORK5CYII='
  const actionImage = 'data:image/png;base64,[encoded data, 29408 characters]'
  const actionButtonImage = 'data:image/png;base64,[encoded data, 7452 characters]'
  const actionButton1Image = 'data:image/png;base64,[encoded data, 7700 characters]'
  const actionButton2Image = 'data:image/png;base64,[encoded data, 8060 characters]'
  const actionButton3Image = 'data:image/png;base64,[encoded data, 8348 characters]'
  const mediaImage = 'data:image/png;base64,[encoded data, 8308 characters]'

  Blockly.Blocks['oh_sendCloudNotification'] = {
    init: function () {
      const userImageField = new Blockly.FieldImage(usersImage, 15, 15, undefined, this.onClickUser)
      userImageField.setTooltip('Comma separated users. If not provided it results into a broadcast')
      const iconImageField = new Blockly.FieldImage(iconImage, 15, 15, undefined, this.onClickIcon)
      iconImageField.setTooltip('Icon name')
      const tagImageField = new Blockly.FieldImage(tagImage, 15, 15, undefined, this.onClickTag)
      tagImageField.setTooltip('Tag')
      const headerTitleImageField = new Blockly.FieldImage(headerTitleImage, 15, 15, undefined, this.onClickHeaderTitle)
      headerTitleImageField.setTooltip('Header title of Notification')
      const referenceImageField = new Blockly.FieldImage(referenceImage, 15, 15, undefined, this.onClickReference)
      referenceImageField.setTooltip('Reference of the message')
      const actionImageField = new Blockly.FieldImage(actionImage, 15, 15, undefined, this.onClickAction)
      actionImageField.setTooltip('Action command to be sent')
      const actionButton1ImageField = new Blockly.FieldImage(actionButton1Image, 15, 15, undefined, this.onClickActionButton1)
      actionButton1ImageField.setTooltip('Action Button 1 command and action')
      const actionButton2ImageField = new Blockly.FieldImage(actionButton2Image, 15, 15, undefined, this.onClickActionButton2)
      actionButton2ImageField.setTooltip('Action Button 2 command and action')
      const actionButton3ImageField = new Blockly.FieldImage(actionButton3Image, 15, 15, undefined, this.onClickActionButton3)
      actionButton3ImageField.setTooltip('Action Button 3 command and action')
      const mediaImageField = new Blockly.FieldImage(mediaImage, 15, 15, undefined, this.onClickMedia)
      mediaImageField.setTooltip('A Media URL that can be clicked and can be accessed publicly to be shown with the notification')

      this.appendValueInput('message')
        .setCheck('String')
        .appendField(userImageField, 'imgUsers')
        .appendField(headerTitleImageField, 'headerTitleIcon')
        .appendField(iconImageField, 'imgIcon')
        .appendField(tagImageField, 'tagIcon')
        .appendField(referenceImageField, 'tagIcon')
        .appendField(mediaImageField, 'mediaIcon')
        .appendField(actionImageField, 'tagIcon')
        .appendField(actionButton1ImageField, 'actionButton1Icon')
        .appendField(actionButton2ImageField, 'actionButton2Icon')
        .appendField(actionButton3ImageField, 'actionButton3Icon')
        .appendField(new Blockly.FieldDropdown([['send notification', 'push'], ['send log', 'log']]), 'type')

      this.updateShape(this.hasUser, true, this.hasIconInfo, this.hasTag, this.hasHeaderTitle, this.hasReferenceId, this.hasAction, this.hasActionButton1, this.hasMedia)

      this.setPreviousStatement(true, null)
      this.setNextStatement(true, null)
      this.setInputsInline(false)
      this.setColour(40)
      this.setTooltip('Sends a notification to the cloud log only, not to any device (requires openHAB Cloud Connector)')
      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#sendCloudNotification')
    },
    updateShape: function (hasUser, addTextBlock, hasIconInfo, hasTag, hasHeaderTitle, hasReferenceId, hasAction, hasActionButton1, hasActionButton2, hasActionButton3, hasMedia) {
      this.hasUser = hasUser
      this.hasIconInfo = hasIconInfo
      this.hasTag = hasTag
      this.hasHeaderTitle = hasHeaderTitle
      this.hasReferenceId = hasReferenceId
      this.hasMedia = hasMedia
      this.hasAction = hasAction
      this.hasActionButton1 = hasActionButton1
      this.hasActionButton2 = hasActionButton2
      this.hasActionButton3 = hasActionButton3

      const blockSequence = ['usersInput', 'headerTitle', 'icon', 'tag', 'reference', 'media', 'action', 'actionButton1', 'actionButton2', 'actionButton3']

      /**
       * Adds a "shadow" text input to the parent block
       *
       * @param {*} parentConnection
       * @param {string} tooltip
       * @param {String} [blockType=text|
       */
      function addBlockInput (parentConnection, tooltip, blockType = 'text') {
        const textUsersBlock = this.workspace.newBlock(blockType)
        textUsersBlock.setTooltip(tooltip)
        textUsersBlock.initSvg()
        textUsersBlock.render()
        parentConnection.connect(textUsersBlock.outputConnection)
      }

      /**
       * Removes the block "shadow" text input from the block
       *
       * @param {Input} parentConnection
       */
      function removeTextInput (parentConnection) {
        const targetBlock = parentConnection.targetBlock()
        if (targetBlock) {
          targetBlock.unplug(true)
          targetBlock.dispose(true)
        }
      }

      /**
       * Show or hide this particular block
       *
       * @param {boolean} toggleOn show (true) / hide (false) block
       * @param {string} blockName name of the block to be toggled
       * @param {string} label label for the preceding label block
       * @param {string} tooltip tooltip for the input block
       * @param {string} [blockTypeCheck=String] checks the input by this block type
       * @param {string} [shadowBlock=text] shadow block
       */
      function toogleBlock (toggleOn, blockName, label, tooltip, blockTypeCheck = 'String', shadowBlock = 'text') {
        if (toggleOn) {
          if (!this.getInput(blockName)) {
            const usersInput = this.appendValueInput(blockName)
              .setCheck(blockTypeCheck)
              .appendField(label)

            let startIndex = blockSequence.indexOf(blockName) + 1
            let blockAfter
            // start from our block, iterate through all possible blocks and insert before the first actually existing one
            for (let blockIndex = startIndex; blockIndex < blockSequence.length; blockIndex++) {
              if (this.getInput(blockSequence[blockIndex])) {
                blockAfter = blockSequence[blockIndex]
                break
              }
            }

            if (blockAfter) {
              this.moveInputBefore(blockName, blockAfter)
            }
            if (addTextBlock) {
              const parentConnection = usersInput.connection
              addBlockInput.call(this, parentConnection, tooltip, shadowBlock)
            }
          }
        } else {
          if (this.getInput(blockName)) {
            const parentConnection = this.getInput(blockName).connection
            removeTextInput(parentConnection)
            this.removeInput(blockName)
          }
        }
      }

      toogleBlock.call(this, hasUser, 'usersInput', 'to Users ', 'Add comma separated users. If not provided it results into a broadcast to everyone registered in the cloud', 'String')
      toogleBlock.call(this, hasHeaderTitle, 'headerTitle', 'with Header Title ', 'Provide title', 'String')
      toogleBlock.call(this, hasIconInfo, 'icon', 'with Icon ', 'Provide icon name', 'String')
      toogleBlock.call(this, hasTag, 'tag', 'with Tag ', 'Provide tag', 'String')
      toogleBlock.call(this, hasReferenceId, 'reference', 'with Reference ID ', 'Provide message reference ID', 'String')
      toogleBlock.call(this, hasMedia, 'media', 'with Media URL ', 'Provide a public Media URL that should be shown as part of the notification', 'String')
      toogleBlock.call(this, hasAction, 'action', 'with On-Click Action ', 'Provide cloud-notification-action', ['oh_notificationAction', 'String'], 'oh_cloudNotification_commandAction')
      toogleBlock.call(this, hasActionButton1, 'actionButton1', 'with Action Button 1', 'Action Button 1: Title = cloud-notification-action', ['oh_notificationActionButton', 'String'], 'oh_cloudNotificationButton')
      toogleBlock.call(this, hasActionButton2, 'actionButton2', 'with Action Button 2', 'Action Button 2: Title = cloud-notification-action', ['oh_notificationActionButton', 'String'], 'oh_cloudNotificationButton')
      toogleBlock.call(this, hasActionButton3, 'actionButton3', 'with Action Button 3', 'Action Button 3: Title = cloud-notification-action', ['oh_notificationActionButton', 'String'], 'oh_cloudNotificationButton')
    },
    onClickUser () {
      let block = this.getSourceBlock()
      block.hasUser = !block.hasUser
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickIcon () {
      let block = this.getSourceBlock()
      block.hasIconInfo = !block.hasIconInfo
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickTag () {
      let block = this.getSourceBlock()
      block.hasTag = !block.hasTag
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickHeaderTitle () {
      let block = this.getSourceBlock()
      block.hasHeaderTitle = !block.hasHeaderTitle
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickReference () {
      let block = this.getSourceBlock()
      block.hasReferenceId = !block.hasReferenceId
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickAction () {
      let block = this.getSourceBlock()
      block.hasAction = !block.hasAction
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickActionButton1 () {
      let block = this.getSourceBlock()
      block.hasActionButton1 = !block.hasActionButton1
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickActionButton2 () {
      let block = this.getSourceBlock()
      block.hasActionButton2 = !block.hasActionButton2
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickActionButton3 () {
      let block = this.getSourceBlock()
      block.hasActionButton3 = !block.hasActionButton3
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    onClickMedia () {
      let block = this.getSourceBlock()
      block.hasMedia = !block.hasMedia
      block.updateShape(block.hasUser, true, block.hasIconInfo, block.hasTag, block.hasHeaderTitle, block.hasReferenceId, block.hasAction, block.hasActionButton1, block.hasActionButton2, block.hasActionButton3, block.hasMedia)
    },
    mutationToDom: function () {
      let container = Blockly.utils.xml.createElement('mutation')
      container.setAttribute('hasUser', this.hasUser)
      container.setAttribute('hasIconInfo', this.hasIconInfo)
      container.setAttribute('hasTag', this.hasTag)
      container.setAttribute('hasHeaderTitle', this.hasHeaderTitle)
      container.setAttribute('hasReferenceId', this.hasReferenceId)
      container.setAttribute('hasMedia', this.hasMedia)
      container.setAttribute('hasAction', this.hasAction)
      container.setAttribute('hasActionButton1', this.hasActionButton1)
      container.setAttribute('hasActionButton2', this.hasActionButton2)
      container.setAttribute('hasActionButton3', this.hasActionButton3)
      return container
    },
    domToMutation: function (xmlElement) {
      let hasUser = xmlElement.getAttribute('hasUser') === 'true'
      let hasIconInfo = xmlElement.getAttribute('hasIconInfo') === 'true'
      let hasTag = xmlElement.getAttribute('hasTag') === 'true'
      let hasHeaderTitle = xmlElement.getAttribute('hasHeaderTitle') === 'true'
      let hasReferenceId = xmlElement.getAttribute('hasReferenceId') === 'true'
      let hasMedia = xmlElement.getAttribute('hasMedia') === 'true'
      let hasAction = xmlElement.getAttribute('hasAction') === 'true'
      let hasActionButton1 = xmlElement.getAttribute('hasActionButton1') === 'true'
      let hasActionButton2 = xmlElement.getAttribute('hasActionButton2') === 'true'
      let hasActionButton3 = xmlElement.getAttribute('hasActionButton3') === 'true'
      this.updateShape(hasUser, false, hasIconInfo, hasTag, hasHeaderTitle, hasReferenceId, hasAction, hasActionButton1, hasActionButton2, hasActionButton3, hasMedia)
    }
  }

  javascriptGenerator.forBlock['oh_sendCloudNotification'] = function (block) {
    const message = javascriptGenerator.valueToCode(block, 'message', javascriptGenerator.ORDER_ATOMIC)
    const type = block.getFieldValue('type')
    const icon = javascriptGenerator.valueToCode(block, 'icon', javascriptGenerator.ORDER_ATOMIC)
    const tag = javascriptGenerator.valueToCode(block, 'tag', javascriptGenerator.ORDER_ATOMIC)
    const headerTitle = javascriptGenerator.valueToCode(block, 'headerTitle', javascriptGenerator.ORDER_ATOMIC)
    const reference = javascriptGenerator.valueToCode(block, 'reference', javascriptGenerator.ORDER_ATOMIC)
    const media = javascriptGenerator.valueToCode(block, 'media', javascriptGenerator.ORDER_ATOMIC)
    const action = javascriptGenerator.valueToCode(block, 'action', javascriptGenerator.ORDER_ATOMIC)
    const actionType = (action !== '') ? blockGetCheckedInputType(block, 'action') : undefined
    const actionButton1 = javascriptGenerator.valueToCode(block, 'actionButton1', javascriptGenerator.ORDER_ATOMIC)
    const actionButton1Type = (actionButton1 !== '') ? blockGetCheckedInputType(block, 'actionButton1') : undefined
    const actionButton2 = javascriptGenerator.valueToCode(block, 'actionButton2', javascriptGenerator.ORDER_ATOMIC)
    const actionButton2Type = (actionButton2 !== '') ? blockGetCheckedInputType(block, 'actionButton2') : undefined
    const actionButton3 = javascriptGenerator.valueToCode(block, 'actionButton3', javascriptGenerator.ORDER_ATOMIC)
    const actionButton3Type = (actionButton3 !== '') ? blockGetCheckedInputType(block, 'actionButton3') : undefined
    const users = javascriptGenerator.valueToCode(block, 'usersInput', javascriptGenerator.ORDER_ATOMIC)

    function getActionButtonCode (titleAndAction, buttonActionType) {
      let actionButtonCode
      if (buttonActionType === 'String') {
        titleAndAction = titleAndAction.replace(/'/g, '').split('=')
        if (titleAndAction.length === 2) {
          let title = titleAndAction[0]
          let buttonAction = titleAndAction[1].replace(/ /g, '')
          actionButtonCode = `.addActionButton('${title}','${buttonAction}')`
        }
      } else {
        actionButtonCode = titleAndAction
      }
      return actionButtonCode
    }

    const iconCode = (icon === '') ? '' : `.withIcon(${icon})`
    const tagCode = (tag === '') ? '' : `.withTag(${tag})`
    const headerTitleCode = (headerTitle === '') ? '' : `.withTitle(${headerTitle})`
    const referenceCode = (reference === '') ? '' : `.withReferenceId(${reference})`
    const mediaCode = (media === '') ? '' : `.withMediaAttachmentUrl(${media})`
    const actionCode = (action === '') ? '' : `.withOnClickAction(${action})`
    const usersCode = (users === '') ? '' : `.addUserId(...${users}.split(','))`

    const actionButton1Code = getActionButtonCode(actionButton1, actionButton1Type)
    const actionButton2Code = getActionButtonCode(actionButton2, actionButton2Type)
    const actionButton3Code = getActionButtonCode(actionButton3, actionButton3Type)
    const logOnlyCode = (type === 'push') ? '' : '.logOnly()'

    return `actions.notificationBuilder(${message})${usersCode}${headerTitleCode}${iconCode}${tagCode}${referenceCode}${mediaCode}${actionCode}${actionButton1Code}${actionButton2Code}${actionButton3Code}${logOnlyCode}.send()\n`
  }

  Blockly.Blocks['oh_cloudNotificationButton'] = {
    init: function () {
      const actionButtonImageField = new Blockly.FieldImage(actionButtonImage, 15, 15, undefined)
      this.appendValueInput('label')
        .appendField(actionButtonImageField, 'actionButtonHint')
        .appendField('label')
        .setCheck('String')
      this.appendValueInput('action')
        .appendField('action')
        .setCheck(['String', 'oh_notificationAction'])
      this.setInputsInline(false)
      this.setColour(40)
      this.setTooltip('Notification Button with label and action')
      this.setOutput(true, 'oh_notificationActionButton')

      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#cloudNotificationButton')
    }
  }

  javascriptGenerator.forBlock['oh_cloudNotificationButton'] = function (block) {
    const label = javascriptGenerator.valueToCode(block, 'label', javascriptGenerator.ORDER_ATOMIC).replace(/'/g, '')
    const action = javascriptGenerator.valueToCode(block, 'action', javascriptGenerator.ORDER_ATOMIC)
    return [`.addActionButton('${label}', ${action})`, javascriptGenerator.ORDER_ATOMIC]
  }

  Blockly.Blocks['oh_cloudNotification_commandAction'] = {
    init: function () {
      const actionImageField = new Blockly.FieldImage(actionImage, 15, 15, undefined)
      this.appendValueInput('command')
        .appendField(actionImageField, 'actionHint')
        .appendField('send command ')
        .setCheck('String')
      this.appendValueInput('itemName')
        .appendField('to item ')
        .setCheck('oh_item')
      this.setInputsInline(false)
      this.setColour(40)
      this.setTooltip('An action that sends a command to an item, like ON to KitchenLights')
      this.setOutput(true, 'oh_notificationAction')

      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#command-action')
    }
  }

  javascriptGenerator.forBlock['oh_cloudNotification_commandAction'] = function (block) {
    const command = javascriptGenerator.valueToCode(block, 'command', javascriptGenerator.ORDER_ATOMIC)
    const commandType = (command !== '') ? blockGetCheckedInputType(block, 'command') : undefined
    const itemName = javascriptGenerator.valueToCode(block, 'itemName', javascriptGenerator.ORDER_ATOMIC).replace(/'/g, '')
    const itemType = (itemName !== '') ? blockGetCheckedInputType(block, 'itemName') : undefined
    const commandCode = '\'command:' +
      ((itemType === '') ? '\' + ' + itemName + ' + \':\' ' : `${itemName}:'`) +
      ((commandType === '') ? ' + ' + command : ` + ${command}`)
    return [commandCode, javascriptGenerator.ORDER_ATOMIC]
  }

  Blockly.Blocks['oh_cloudNotification_uiAction'] = {
    init: function () {
      const actionImageField = new Blockly.FieldImage(actionImage, 15, 15, undefined)
      this.appendDummyInput()
        .appendField(actionImageField, 'actionHint')
        .appendField('Call ')
        .appendField(new Blockly.FieldDropdown([['Basic UI', 'ui:/basicui/app?'], ['UI absolute Path', 'ui:'], ['Main UI path', 'ui:navigate:'], ['Main UI popup', 'ui:popup:'], ['URL', '']]), 'command')
      this.appendValueInput('path')
        .appendField('with ')
        .setCheck('String')
      this.setInputsInline(false)
      this.setColour(40)

      this.setTooltip(() => {
        const commandType = this.getFieldValue('command')
        const TIP = {
          'ui:/basicui/app?': 'Provide valid sitemap parameters in the form w=nnnn&sitemap=mysitemap',
          'ui:': 'Provide the path that follows your openhab domain name, e.g /some/absolute/path like /page/rollershutter_firstfloor',
          'ui:navigate:': '',
          'ui:popup:': 'Provide the name of a page to be shown as a popup, e.g. page_phones',
          '': 'Provide a valid absolute URL like https://openhab.org'
        }
        return TIP[commandType]
      })
      this.setOutput(true, 'oh_notificationAction')

      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#ui-action')
    }
  }

  javascriptGenerator.forBlock['oh_cloudNotification_uiAction'] = function (block) {
    const command = block.getFieldValue('command')
    const path = javascriptGenerator.valueToCode(block, 'path', javascriptGenerator.ORDER_ATOMIC).replace(/'/g, '')
    const pathType = (path !== '') ? blockGetCheckedInputType(block, 'path') : undefined
    const pathCode = (pathType === '') ? ' + ' + path : ` + '${path}'`
    const uiActionCode = `'${command}'${pathCode}`
    return [uiActionCode, javascriptGenerator.ORDER_ATOMIC]
  }

  Blockly.Blocks['oh_hideCloudNotification'] = {
    init: function () {
      this.appendValueInput('reference')
        .appendField('hide notification by reference ID')
      this.appendValueInput('tag')
        .appendField('or tag ')
      this.setPreviousStatement(true, null)
      this.setNextStatement(true, null)
      this.setInputsInline(false)
      this.setColour(40)
      this.setTooltip('Hides the notification with the given reference ID or tag')
      this.setHelpUrl('https://www.openhab.org/docs/configuration/blockly/rules-blockly-notifications.html#hide-notification')
    }
  }

  javascriptGenerator.forBlock['oh_hideCloudNotification'] = function (block) {
    const reference = javascriptGenerator.valueToCode(block, 'reference', javascriptGenerator.ORDER_ATOMIC)
    const tag = javascriptGenerator.valueToCode(block, 'tag', javascriptGenerator.ORDER_ATOMIC)
    const tagCode = (tag === '') ? '' : `.withTag(${tag})`
    const referenceCode = (reference === '') ? '' : `.withReferenceId(${reference})`
    return `actions.notificationBuilder("hide notification")${referenceCode}${tagCode}.hide().send();\n`
  }
}
