class Index extends App.ControllerIntegrationBase
  featureIntegration: 'pgp_integration'
  featureName: 'PGP'
  featureConfig: 'pgp_config'
  description: [
    ['PGP (Pretty Good Privacy) is a widely accepted method (or more precisely, a protocol) for sending digitally signed and encrypted messages.']
  ]
  events:
    'change .js-switch input': 'switch'

  render: =>
    super
    new Form(
      el: @$('.js-form')
    )

    new App.HttpLog(
      el: @$('.js-log')
      facility: 'PGP'
    )

class Form extends App.Controller
  events:
    'click .js-addPublicKey': 'addPublicKey'
    'click .js-addPrivateKey': 'addPrivateKey'
    'click .js-updateGroup': 'updateGroup'

  constructor: ->
    super
    @render()

  currentConfig: ->
    App.Setting.get('pgp_config')

  setConfig: (value) ->
    App.Setting.set('pgp_config', value, {notify: true})

  render: =>
    @config = @currentConfig()

    @html App.view('integration/pgp')(
      config: @config
    )
    @keyList()
    @groupList()

  keyList: =>
    new List(el: @$('.js-keyList'))

  groupList: =>
    new Group(
      el: @$('.js-groupList')
      config: @config
    )

  addPublicKey: =>
    new PublicKey(
      callback: @keyList
    )

  addPrivateKey: =>
    new PrivateKey(
      callback: @keyList
    )

  updateGroup: (e) =>
    params = App.ControllerForm.params(e)
    @setConfig(params)

class PublicKey extends App.ControllerModal
  buttonClose: true
  buttonCancel: true
  buttonSubmit: 'Add'
  autoFocusOnFirstInput: false
  head: 'Add Public Key'
  large: true

  content: ->

    # show start dialog
    content = $(App.view('integration/pgp_public_key_add')(
      head: 'Add Public Key'
    ))
    content

  onSubmit: (e) =>
    params = new FormData($(e.currentTarget).closest('form').get(0))
    params.set('try', true)
    if _.isEmpty(params.get('data'))
      params.delete('data')
    @formDisable(e)

    @ajax(
      id:          'pgp-public_key-add'
      type:        'POST'
      url:         "#{@apiPath}/integration/pgp/public_key"
      processData: false
      contentType: false
      cache:       false
      data:        params
      success:     (data, status, xhr) =>
        @close()
        @callback()
      error: (data) =>
        @close()
        details = data.responseJSON || {}
        @notify
          type:    'error'
          msg:     App.i18n.translateContent(details.error_human || details.error || 'The import failed.')
          timeout: 6000
    )

class PrivateKey extends App.ControllerModal
  buttonClose: true
  buttonCancel: true
  buttonSubmit: 'Add'
  autoFocusOnFirstInput: false
  head: 'Add Private Key'
  large: true

  content: ->

    # show start dialog
    content = $(App.view('integration/pgp_private_key_add')(
      head: 'Add Private Key'
    ))
    content

  onSubmit: (e) =>
    params = new FormData($(e.currentTarget).closest('form').get(0))
    params.set('try', true)
    if _.isEmpty(params.get('data'))
      params.delete('data')
    @formDisable(e)

    @ajax(
      id:          'pgp-private_key-add'
      type:        'POST'
      url:         "#{@apiPath}/integration/pgp/private_key"
      processData: false
      contentType: false
      cache:       false
      data:        params
      success:     (data, status, xhr) =>
        @close()
        @callback()
      error: (data) =>
        @close()
        details = data.responseJSON || {}
        @notify
          type:    'error'
          msg:     App.i18n.translateContent(details.error_human || details.error || 'The import failed.')
          timeout: 6000
    )


class List extends App.Controller
  events:
    'click .js-remove': 'remove'

  constructor: ->
    super
    @load()

  load: =>
    @ajax(
      id:    'pgp-list'
      type:  'GET'
      url:   "#{@apiPath}/integration/pgp/public_key"
      success: (data, status, xhr) =>
        @render(data)

      error: (data, status) =>

        # do not close window if request is aborted
        return if status is 'abort'

        details = data.responseJSON || {}
        @notify(
          type: 'error'
          msg:  App.i18n.translateContent(details.error_human || details.error || 'Loading failed.')
        )

        # do something
    )

  render: (data) =>
    @html App.view('integration/pgp_list')(
      keyPairs: data
    )

  remove: (e) =>
    e.preventDefault()
    id = $(e.currentTarget).parents('tr').data('id')
    return if !id

    @ajax(
      id:    'pgp-list'
      type:  'DELETE'
      url:   "#{@apiPath}/integration/pgp/public_key"
      data:  JSON.stringify(id: id)
      success: (data, status, xhr) =>
        @load()

      error: (data, status) =>

        # do not close window if request is aborted
        return if status is 'abort'

        details = data.responseJSON || {}
        @notify(
          type: 'error'
          msg:  App.i18n.translateContent(details.error_human || details.error || 'Server operation failed.')
        )
    )

class Group extends App.Controller
  constructor: ->
    super
    @render()

  render: (data) =>
    groups = App.Group.search(sortBy: 'name', filter: active: true)
    @html App.view('integration/pgp_group')(
      groups: groups
    )
    for group in groups
      for type, selector of { default_sign: 'js-signDefault', default_encryption: 'js-encryptionDefault' }
        selected = true
        if @config?.group_id && @config.group_id[type]
          selected = @config.group_id[type][group.id.toString()]
        selection = App.UiElement.boolean.render(
          name: "group_id::#{type}::#{group.id}"
          multiple: false
          null: false
          nulloption: false
          value: selected
          class: 'form-control--small'
        )
        @$("[data-id=#{group.id}] .#{selector}").html(selection)

class State
  @current: ->
    App.Setting.get('pgp_integration')

App.Config.set(
  'Integrationpgp'
  {
    name: 'PGP'
    target: '#system/integration/pgp'
    description: 'PGP enables you to send digitally signed and encrypted messages.'
    controller: Index
    state: State
  }
  'NavBarIntegrations'
)
