'use strict'

var Promise = require('q');
var _ = require('./lodash')

module.exports = function(service) {
  return function clear(def) {

    // Clear a single or multiple column definitions
    if (def) {
      def = _.isArray(def) ? def : [def]
    }

    if (!def) {
      // Clear all of the column defenitions
      return Promise.all(_.map(service.columns, disposeColumn))
        .then(function() {
          service.columns = []
          return service
        })

    }


    return Promise.all(_.map(def, function(d) {
        if (_.isObject(d)) {
          d = d.key
        }
        // Clear the column
        var column = _.remove(service.columns, function(c) {
          if (_.isArray(d)) {
            return !_.xor(c.key, d).length
          }
          if (c.key === d) {
            if (c.dynamicReference) {
              return false
            }
            return true
          }
        })[0]

        if (!column) {
          // console.info('Attempted to clear a column that is required for another query!', c)
          return
        }

        disposeColumn(column)
      }))
      .then(function() {
        return service
      })

    function disposeColumn(column) {
      // Dispose the dimension
      var disposalActions = _.map(column.removeListeners, function(listener) {
        return Promise.resolve(listener())
      })
      var filterKey = column.complex ? JSON.stringify(column.key) : column.key
      delete service.filters[filterKey]
      disposalActions.push(Promise.resolve(column.dimension.dispose()))
      return Promise.all(disposalActions)
    }

  }
}

@@ -1209,42 +1209,109 @@
     
-// Dispose the dimension%0A      var
+var disposalActions = %5B%5D%0A        // Dispose the dimension%0A      if (column.removeListeners) %7B%0A       
  dis
@@ -1380,24 +1380,26 @@
 ) %7B%0A        
+  
 return Promi
@@ -1427,19 +1427,29 @@
 )%0A      
+  
 %7D)%0A
+      %7D%0A
       va
@@ -1559,16 +1559,46 @@
 terKey%5D%0A
+      if(column.dimension)%7B%0A  
       di
@@ -1661,16 +1661,24 @@
 ose()))%0A
+      %7D%0A
       re

Clear safety