import Dom from '../../libs/dom'
import Widget from '../widget'

class ButtonGroup extends Widget {
  constructor(layer, screen) {
    super(layer, screen)
    this._container = Dom.createElement('div', 'tab-container comp', this.el)
    this.on('resize', () => {
      this.resize()
    })
  }

  setPaint() {
    this.setListener()
    this._container.innerHTML = ''
    let newPaint = this._mergePaint()
    Dom.css(this._container, {
      fontSize: newPaint.style.fontSize + 'px',
      border: `1px solid ${newPaint.style.borderColor}`
    })
    var data = newPaint.tabs
    for (let i = 0; i < data.length; i++) {
      var tabItem
      if (i === 0) {
        tabItem = Dom.createElement('div', 'tab-item active', this._container)
      } else {
        tabItem = Dom.createElement('div', 'tab-item', this._container)
      }
      if (newPaint.style.orient === 'horizontal') {
        Dom.css(tabItem, {
          display: 'inline-block',
          width: 100 / data.length + '%',
          lineHeight: this.el.style.height
        })
      } else {
        let height = this.layer.layout.height / data.length
        let lineHeight = height < 40 ? 40 : height
        Dom.css(tabItem, {
          display: 'block',
          width: '100%',
          height: height + 'px',
          lineHeight: lineHeight + 'px'
        })
      }
      tabItem.innerText = data[i].label
      tabItem.onclick = e => {
        let tabName = e.target.innerText
        let tabs = this._container.getElementsByClassName('tab-item')
        for (let j = 0; j < tabs.length; j++) {
          Dom.removeClass(tabs[j], 'active')
        }
        Dom.addClass(e.target, 'active')
        this.tabAction(data, tabName)
        this.updateStyle(newPaint.style)
        this.fire('tabChange', { name: tabName })
      }
    }
    this.updateStyle(newPaint.style)
  }

  tabAction(data, tabName) {
    let events = this.layer.events
    let index = data.findIndex(d => d.label === tabName)
    let vars = data[index].vars
    for (let k in vars) {
      this._screen.store.patchState(events[k].alias, vars[k])
    }
  }

  resize() {
    let tabs = this._container.getElementsByClassName('tab-item')
    for (let i = 0; i < tabs.length; i++) {
      Dom.css(tabs[i], {
        lineHeight: this.el.style.height
      })
    }
  }

  updateStyle(style) {
    let tabItems = this._container.querySelectorAll('.tab-item')
    let activeTabItem = this._container.querySelector('.tab-item.active')
    for (let i = 0; i < tabItems.length; i++) {
      Dom.css(tabItems[i], {
        color: style.fontColor,
        background: 'transparent'
      })
    }
    Dom.css(activeTabItem, {
      color: style.highlightColor,
      background: style.activeBackground
    })
  }
}

export default ButtonGroup
