import "../../../../echarts@5.4.3/node_modules/echarts/lib/echarts.mjs";
import "./WordCloudSeries.mjs";
import "./WordCloudView.mjs";
import WordCloud from "./layout.mjs";
import { registerLayout, registerPreprocessor } from "../../../../echarts@5.4.3/node_modules/echarts/lib/core/echarts.mjs";
import { getLayoutRect } from "../../../../echarts@5.4.3/node_modules/echarts/lib/util/layout.mjs";
import { linearMap } from "../../../../echarts@5.4.3/node_modules/echarts/lib/util/number.mjs";
import { isArray, each } from "../../../../zrender@5.4.4/node_modules/zrender/lib/core/util.mjs";
import { capitalFirst } from "../../../../echarts@5.4.3/node_modules/echarts/lib/util/format.mjs";
if (!WordCloud.isSupported) {
  throw new Error("Sorry your browser not support wordCloud");
}
function updateCanvasMask(maskCanvas) {
  var ctx = maskCanvas.getContext("2d");
  var imageData = ctx.getImageData(0, 0, maskCanvas.width, maskCanvas.height);
  var newImageData = ctx.createImageData(imageData);
  var toneSum = 0;
  var toneCnt = 0;
  for (var i = 0; i < imageData.data.length; i += 4) {
    var alpha = imageData.data[i + 3];
    if (alpha > 128) {
      var tone = imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2];
      toneSum += tone;
      ++toneCnt;
    }
  }
  var threshold = toneSum / toneCnt;
  for (var i = 0; i < imageData.data.length; i += 4) {
    var tone = imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2];
    var alpha = imageData.data[i + 3];
    if (alpha < 128 || tone > threshold) {
      newImageData.data[i] = 0;
      newImageData.data[i + 1] = 0;
      newImageData.data[i + 2] = 0;
      newImageData.data[i + 3] = 0;
    } else {
      newImageData.data[i] = 255;
      newImageData.data[i + 1] = 255;
      newImageData.data[i + 2] = 255;
      newImageData.data[i + 3] = 255;
    }
  }
  ctx.putImageData(newImageData, 0, 0);
}
registerLayout(function(ecModel, api) {
  ecModel.eachSeriesByType("wordCloud", function(seriesModel) {
    var gridRect = getLayoutRect(
      seriesModel.getBoxLayoutParams(),
      {
        width: api.getWidth(),
        height: api.getHeight()
      }
    );
    var keepAspect = seriesModel.get("keepAspect");
    var maskImage = seriesModel.get("maskImage");
    var ratio = maskImage ? maskImage.width / maskImage.height : 1;
    keepAspect && adjustRectAspect(gridRect, ratio);
    var data = seriesModel.getData();
    var canvas = document.createElement("canvas");
    canvas.width = gridRect.width;
    canvas.height = gridRect.height;
    var ctx = canvas.getContext("2d");
    if (maskImage) {
      try {
        ctx.drawImage(maskImage, 0, 0, canvas.width, canvas.height);
        updateCanvasMask(canvas);
      } catch (e) {
        console.error("Invalid mask image");
        console.error(e.toString());
      }
    }
    var sizeRange = seriesModel.get("sizeRange");
    var rotationRange = seriesModel.get("rotationRange");
    var valueExtent = data.getDataExtent("value");
    var DEGREE_TO_RAD = Math.PI / 180;
    var gridSize = seriesModel.get("gridSize");
    WordCloud(canvas, {
      list: data.mapArray("value", function(value, idx) {
        var itemModel = data.getItemModel(idx);
        return [
          data.getName(idx),
          itemModel.get("textStyle.fontSize", true) || linearMap(value, valueExtent, sizeRange),
          idx
        ];
      }).sort(function(a, b) {
        return b[1] - a[1];
      }),
      fontFamily: seriesModel.get("textStyle.fontFamily") || seriesModel.get("emphasis.textStyle.fontFamily") || ecModel.get("textStyle.fontFamily"),
      fontWeight: seriesModel.get("textStyle.fontWeight") || seriesModel.get("emphasis.textStyle.fontWeight") || ecModel.get("textStyle.fontWeight"),
      gridSize,
      ellipticity: gridRect.height / gridRect.width,
      minRotation: rotationRange[0] * DEGREE_TO_RAD,
      maxRotation: rotationRange[1] * DEGREE_TO_RAD,
      clearCanvas: !maskImage,
      rotateRatio: 1,
      rotationStep: seriesModel.get("rotationStep") * DEGREE_TO_RAD,
      drawOutOfBound: seriesModel.get("drawOutOfBound"),
      shrinkToFit: seriesModel.get("shrinkToFit"),
      layoutAnimation: seriesModel.get("layoutAnimation"),
      shuffle: false,
      shape: seriesModel.get("shape")
    });
    function onWordCloudDrawn(e) {
      var item = e.detail.item;
      if (e.detail.drawn && seriesModel.layoutInstance.ondraw) {
        e.detail.drawn.gx += gridRect.x / gridSize;
        e.detail.drawn.gy += gridRect.y / gridSize;
        seriesModel.layoutInstance.ondraw(
          item[0],
          item[1],
          item[2],
          e.detail.drawn
        );
      }
    }
    canvas.addEventListener("wordclouddrawn", onWordCloudDrawn);
    if (seriesModel.layoutInstance) {
      seriesModel.layoutInstance.dispose();
    }
    seriesModel.layoutInstance = {
      ondraw: null,
      dispose: function() {
        canvas.removeEventListener("wordclouddrawn", onWordCloudDrawn);
        canvas.addEventListener("wordclouddrawn", function(e) {
          e.preventDefault();
        });
      }
    };
  });
});
registerPreprocessor(function(option) {
  var series = (option || {}).series;
  !isArray(series) && (series = series ? [series] : []);
  var compats = ["shadowColor", "shadowBlur", "shadowOffsetX", "shadowOffsetY"];
  each(series, function(seriesItem) {
    if (seriesItem && seriesItem.type === "wordCloud") {
      var textStyle = seriesItem.textStyle || {};
      compatTextStyle(textStyle.normal);
      compatTextStyle(textStyle.emphasis);
    }
  });
  function compatTextStyle(textStyle) {
    textStyle && each(compats, function(key) {
      if (textStyle.hasOwnProperty(key)) {
        textStyle["text" + capitalFirst(key)] = textStyle[key];
      }
    });
  }
});
function adjustRectAspect(gridRect, aspect) {
  var width = gridRect.width;
  var height = gridRect.height;
  if (width > height * aspect) {
    gridRect.x += (width - height * aspect) / 2;
    gridRect.width = height * aspect;
  } else {
    gridRect.y += (height - width / aspect) / 2;
    gridRect.height = width / aspect;
  }
}
