'use strict';

var key = require('./key')
var d3  = require('d3')

function Row (viz) {
  if (!(this instanceof Row)){
    return new Row(viz)
  }
  this.viz = viz
}

Row.prototype.updateSel = function updateSel(sel, expanded, data){
  var self = this
  var update = sel.selectAll('.cxviz-eventloop-row').data(data.eventLoopAgg, key)
  update.enter().append('rect')
    .attr('class', 'cxviz-eventloop-row')
    .on('mouseenter', function(d){ self.mouseEnter(d3.select(this), d)})
    .on('mouseleave', function(d){ self.mouseLeave(d3.select(this), d)})
    .on('click', function(d){ self.click(d3.select(this), d)})

  update.attr('width', this.viz.coords.overallWidth)
    .attr('height', function(d){ return d.cxvEL.layout.height })
    .attr('x', 0)
    .attr('y', function (d) { return d.cxvEL.layout.y })

  update.exit().remove()
}

Row.prototype.clearSel = function clearSel(sel){
  sel.selectAll('.cxviz-eventloop-row').remove()
}


Row.prototype.mouseEnter = function mouseEnter(sel, d){
  this.viz.emit('mouseenter', {
    type: "eventLoop",
    item: d
  })
}

Row.prototype.mouseLeave = function mouseLeave(sel, d){
  this.viz.emit('mouseleave', {
    type: 'eventLoop',
    item: d
  })
}

Row.prototype.click = function click(sel, d){
  this.viz.emit('click', {
    type: 'eventLoop',
    item: d
  })
}

Row.prototype.highlight = function (data) {
  var self = this
  var sel = d3.select(this.viz.el).selectAll('.cxviz-eventloop-row')
  sel.each(function (item) {
    var el = d3.select(this)
    var label = self.viz.label
    var result = (data === item)
    if (el.classed('cxviz-eventloop-selected')) return
    result ? label.expandLabel(item) : label.clipLabel(item)
    el.classed('cxviz-eventloop-highlight', result)
  })
}

Row.prototype.select = function (data) {
  var self = this
  var sel = d3.select(this.viz.el).selectAll('.cxviz-eventloop-row')
  this.viz.label.clipAllLabels()
  this.viz.label.expandLabel(data)
  sel.each(function (item) {
    var label = self.viz.label
    var result = (data === item)
    result ? label.expandLabel(item) : label.clipLabel(item)
    d3.select(this).classed('cxviz-eventloop-selected', result)
  })
}

Row.prototype.clearSelection = function clearSelection(){
  this.viz.svg.selectAll('.cxviz-eventloop-selected')
    .classed('cxviz-eventloop-selected', false)
    .each(function(d){ d.selected = false })
  this.viz.label.clipAllLabels()
}

module.exports = Row
