import { linkNames } from './utils'
import rename from 'rename-prop'

const defaultMessageOptions = {
  as_user: true
}

function normalizeMessageOptions (options) {
  if (options.titleLink) {
    rename(options, 'titleLink', 'title_link')
  }

  return options
}

export default class SlackChannel {
  constructor (slack, channel) {
    this.slack = slack
    this.client = slack.client
    this.webClient = slack.webClient
    this.channel = channel
  }

  getUsers () {
    return this.slack.getUsers()
  }
  getUser (id) {
    return this.slack.getUser(id)
  }
  getUserByName (name) {
    return this.slack.getUserByName(name)
  }

  getChannels () {
    return this.slack.getChannels()
  }
  getChannel (id) {
    return this.slack.getChannel(id)
  }
  getChannelByName (name) {
    return this.slack.getChannelByName(name)
  }

  reply (message, text, opts = undefined) {
    this.send(`@${message.username} ${text}`, opts)
  }

  send (text, opts = undefined) {
    if (typeof opts === 'object' && Object.keys(opts).length > 0) {
      const chatClient = this.slack.web.chat
      chatClient.postMessage(
        this.channel.id,
        linkNames(this.slack, text),
        normalizeMessageOptions({
          ...defaultMessageOptions,
          ...opts
        })
      )
    } else {
      this.client.sendMessage(linkNames(this.slack, text), this.channel.id)
    }
  }

  canExecute (message) {
    return true
  }

  getAdapterName () {
    return this.slack.getAdapterName()
  }

  toString () {
    return `slack:${this.channel.name}`
  }
}

@@ -1,12 +1,53 @@
+import %7B permissions %7D from 'munar-core'%0A
 import %7B lin
@@ -1441,27 +1441,154 @@
 sage
-) %7B%0A    return true
+, command) %7B%0A    const user = message.user.sourceUser%0A    if (user.is_admin) %7B%0A      return true%0A    %7D%0A    return command.role %3C= permissions.NONE
 %0A  %7D

Implement permissions check for commands (#135)