/**
 * bookmark
 */

import uid from '../common/uid'

export default Store => {
  Store.prototype.handleGetSerials = async function () {
    const { store } = window
    store.loaddingSerials = true
    const res = await window.pre.runGlobalAsync('listSerialPorts')
      .catch(store.onError)
    if (res) {
      store.serials = res
    }
    store.loaddingSerials = false
  }
  Store.prototype.setBookmarks = function (items) {
    return window.store.setItems('bookmarks', items)
  }

  Store.prototype.openBookmarks = function (ids) {
    const { store } = window
    ids.forEach(id => {
      store.onSelectBookmark(id)
    })
  }

  Store.prototype.addSshConfigs = function (items) {
    const { store } = window

    const bookmarksToAdd = items.map(t => {
      return {
        term: 'xterm-256color',
        id: uid(),
        type: 'ssh',
        color: '#0088cc',
        ...t
      }
    })
    const ids = bookmarksToAdd.map(d => d.id)
    let sshConfigGroup = store.bookmarkGroups.find(d => d.id === 'sshConfig')
    if (!sshConfigGroup) {
      sshConfigGroup = {
        id: 'sshConfig',
        title: 'ssh configs',
        bookmarkIds: ids
      }
      store.addBookmarkGroup(sshConfigGroup)
    } else {
      store.editItem('sshConfig', {
        bookmarkIds: [
          ...ids,
          ...(sshConfigGroup.bookmarkIds || [])
        ]
      }, 'bookmarkGroups')
    }
    return store.addItems(bookmarksToAdd, 'bookmarks')
  }
}
