var Gradient = require("zrender/lib/graphic/Gradient");

function applyColors(colorFns, data, seriesModel, idx) {
  return Object.keys(colorFns).forEach(function (fnKey) {
    data.setItemVisual(idx, fnKey, colorFns[fnKey](seriesModel.getDataParams(idx)));
  });
}

function _default(ecModel) {
  function encodeColor(seriesModel) {
    var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.normal.color').split('.');
    var borderColorAccessPath = ['itemStyle', 'normal', 'borderColor'];
    var shadowColorAccessPath = ['itemStyle', 'normal', 'shadowColor'];
    var data = seriesModel.getData();
    var color = seriesModel.get(colorAccessPath) // Set in itemStyle
    || seriesModel.getColorFromPalette(seriesModel.get('name')); // Default color

    var borderColor = seriesModel.get(borderColorAccessPath); // FIXME Set color function or use the platte color

    data.setVisual('color', color);
    data.setVisual('borderColor', borderColor); // Only visible series has each data be visual encoded

    if (!ecModel.isSeriesFiltered(seriesModel)) {
      var colors = {
        color: color,
        borderColor: borderColor,
        shadowColor: seriesModel.get(shadowColorAccessPath)
      };
      var colorFns = Object.keys(colors).reduce(function (acc, color) {
        var col = colors[color];

        if (typeof col === 'function' && !(col instanceof Gradient)) {
          acc[color] = col;
        }

        return acc;
      }, {}); // itemStyle in each data item

      data.each(function (idx) {
        var itemModel = data.getItemModel(idx);
        var itemModels = {
          color: itemModel.get(colorAccessPath, true),
          borderColor: itemModel.get(borderColorAccessPath, true),
          shadowColor: itemModel.get(shadowColorAccessPath, true)
        };
        Object.keys(itemModels).forEach(function (name) {
          var itemModel = itemModels[name];

          if (itemModel != null) {
            data.setItemVisual(idx, name, itemModel);
          }
        });
      });
    }
  }

  ecModel.eachRawSeries(encodeColor);
}

module.exports = _default;