import { showContextMenu } from "teselagen-react-components";
import React, { useEffect, useRef, useState } from "react";
import { Button } from "@blueprintjs/core";
import { chromatogramMenu, useShowChromQualScores } from "../../utils/useChromatogramPrefs";
import classNames from "classnames";
export default function Chromatogram(props) {
  var isRowView = props.isRowView,
    chromatogramData = props.chromatogramData,
    row = props.row,
    getGaps = props.getGaps,
    charWidth = props.charWidth;
  var _useShowChromQualScor = useShowChromQualScores(),
    showChromQualScores = _useShowChromQualScor[0];
  var _useState = useState(0.05),
    scalePct = _useState[0],
    setScalePct = _useState[1];
  var _useState2 = useState(false),
    hasDrawnOnce = _useState2[0],
    setHasDrawnOnce = _useState2[1];
  if (props.scalePct) scalePct = props.scalePct;
  if (props.setScalePct) setScalePct = props.setScalePct;
  var canvasRef = useRef();
  var gapsBeforeRow = getGaps(row.start).gapsBefore;
  useEffect(function () {
    if (!chromatogramData || !chromatogramData.baseTraces || !canvasRef.current) {
      return true;
    }
    var painter = new drawTrace({
      isRowView: isRowView,
      showChromQualScores: showChromQualScores,
      peakCanvas: canvasRef.current,
      traceData: chromatogramData,
      charWidth: charWidth,
      startBp: row.start,
      endBp: row.end,
      getGaps: getGaps,
      gapsBeforeRow: gapsBeforeRow,
      scalePct: scalePct
    });
    painter.paintCanvas();
    setHasDrawnOnce(true);
  }, [setHasDrawnOnce, showChromQualScores, chromatogramData, charWidth, row.start, row.end, gapsBeforeRow, isRowView, scalePct, getGaps, canvasRef]);
  var marginLeft = gapsBeforeRow * charWidth;
  return /*#__PURE__*/React.createElement("div", {
    className: classNames("chromatogram", {
      noQualityScores: !showChromQualScores
    }),
    style: {
      position: "relative"
    },
    onContextMenu: function onContextMenu(e) {
      showContextMenu([chromatogramMenu], undefined, e);
    }
  }, /*#__PURE__*/React.createElement(Button, {
    minimal: true,
    "data-tip": "Scale Chromatogram Up",
    className: "scaleChromatogramButtonUp",
    icon: "caret-up",
    onClick: function onClick(e) {
      e.stopPropagation();
      setScalePct(scalePct + 0.01);
    },
    style: {
      zIndex: 10,
      position: "sticky",
      left: 145
    }
  }), /*#__PURE__*/React.createElement(Button, {
    minimal: true,
    "data-tip": "Scale Chromatogram Down",
    className: "scaleChromatogramButtonDown",
    icon: "caret-down",
    onClick: function onClick(e) {
      e.stopPropagation();
      setScalePct(scalePct - 0.01);
    },
    style: {
      zIndex: 10,
      position: "sticky",
      left: 175
    }
  }), /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement("div", {
    className: classNames({
      "chromatogram-trace": true,
      "chromatogram-trace-initialized": hasDrawnOnce
    }),
    style: {
      zIndex: 1,
      position: "relative",
      left: 0,
      // left: posOfSeqRead,
      display: "inline-block"
    }
    // tnr comment back in for start of tooltip work
    // onMouseEnter={() => {
    //   this.setState({ showTooltip: true });
    // }}
    // onMouseLeave={() => {
    //   this.setState({ showTooltip: false });
    // }}
    // onMouseMove={(e) => {
    //   const { row } = this.props;
    //   const boundingRowRect =
    //     this.chromatogramRef.getBoundingClientRect();
    //   let nearestCaretPos;
    //   if (
    //     getClientY(e) > boundingRowRect.top &&
    //     getClientY(e) < boundingRowRect.top + boundingRowRect.height
    //   ) {
    //     if (getClientX(e) - boundingRowRect.left < 0) {
    //       nearestCaretPos = row.start;
    //     } else {
    //       const clickXPositionRelativeToRowContainer =
    //         getClientX(e) - boundingRowRect.left;
    //       const numberOfBPsInFromRowStart = Math.floor(
    //         (clickXPositionRelativeToRowContainer + charWidth / 2) /
    //           charWidth
    //       );
    //       nearestCaretPos = numberOfBPsInFromRowStart + row.start;
    //       if (nearestCaretPos > row.end + 1) {
    //         nearestCaretPos = row.end + 1;
    //       }
    //     }
    //     this.setState({
    //       nearestCaretPos
    //     });
    //     if (this.tooltipRef) {
    //       this.tooltipRef.style.left =
    //         getClientX(e) - boundingRowRect.left + "px";
    //       this.tooltipRef.style.top =
    //         getClientY(e) - boundingRowRect.top + "px";
    //     }
    //     if (this.tooltipHolderRef) {
    //       this.tooltipHolderRef.reposition();
    //     }
    //   }
    // }}
    // ref={(n) => {
    //   if (n) this.chromatogramRef = n;
    // }}
  }, /*#__PURE__*/React.createElement("canvas", {
    style: {
      marginLeft: marginLeft
    },
    ref: canvasRef,
    height: "100"
  })));
}
function drawTrace(_ref) {
  var traceData = _ref.traceData,
    charWidth = _ref.charWidth,
    startBp = _ref.startBp,
    peakCanvas = _ref.peakCanvas,
    endBp = _ref.endBp,
    getGaps = _ref.getGaps,
    gapsBeforeRow = _ref.gapsBeforeRow,
    showChromQualScores = _ref.showChromQualScores,
    scalePct = _ref.scalePct;
  var colors = {
    adenine: "green",
    thymine: "red",
    guanine: "black",
    cytosine: "blue",
    other: "#ac68cc"
  };
  var ctx = peakCanvas.getContext("2d");
  var bottomBuffer = 0;
  var maxHeight = peakCanvas.height;
  var seqLengthWithGaps = endBp - startBp + 1 + getGaps(endBp).gapsBefore - gapsBeforeRow;
  var maxWidth = seqLengthWithGaps * charWidth;
  peakCanvas.width = maxWidth;
  var scaledHeight = maxHeight - bottomBuffer;
  this.drawPeaks = function (traceType, lineColor) {
    ctx.beginPath();
    //loop through base positions [ 43, 53, 70, 77, ...]
    // looping through the entire sequence length
    var _loop = function _loop(baseIndex) {
      // each base's beginning and end of its peak
      // grab the start and end (43, 53) , (53, 70) ...
      // looping through each base's peak
      var traceForIndex = traceData.baseTraces[baseIndex][traceType];
      var gapsBefore = getGaps(baseIndex - 1).gapsBefore || 0;
      var gapsAt = getGaps(baseIndex).gapsBefore;
      var startXPosition = (baseIndex + gapsAt - startBp - gapsBeforeRow) * charWidth;
      var hasGaps = gapsBefore !== gapsAt;
      var traceLength = traceForIndex.length;
      var tracePointSpacing = charWidth / traceLength;
      // eslint-disable-next-line no-loop-func
      traceForIndex.forEach(function (_tracePoint, tracePointIndex) {
        var tracePoint = scaledHeight - scalePct * _tracePoint;
        if (hasGaps && tracePointIndex === 0) {
          ctx.moveTo(startXPosition, tracePoint);
        }
        ctx.lineTo(startXPosition + tracePointSpacing * tracePointIndex, tracePoint);
      });
    };
    for (var baseIndex = startBp; baseIndex <= endBp; baseIndex++) {
      _loop(baseIndex);
    }
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  };
  this.drawQualityScoreHistogram = function () {
    if (!traceData.qualNums || !showChromQualScores) return;
    var qualMax = Math.max.apply(Math, traceData.qualNums);
    var scalePctQual = scaledHeight / qualMax;
    for (var baseIndex = startBp; baseIndex <= endBp; baseIndex++) {
      var gapsAt = getGaps(baseIndex).gapsBefore;
      var startXPosition = (baseIndex + gapsAt - startBp - gapsBeforeRow) * charWidth;
      ctx.rect(startXPosition, scaledHeight - traceData.qualNums[baseIndex] * scalePctQual, charWidth, traceData.qualNums[baseIndex] * scalePctQual);
    }
    ctx.fillStyle = "#cfc3c3";
    ctx.fill();
    ctx.strokeStyle = "#e9e3f4";
    ctx.stroke();
  };
  this.paintCanvas = function () {
    this.drawQualityScoreHistogram();
    this.drawPeaks("aTrace", colors.adenine);
    this.drawPeaks("tTrace", colors.thymine);
    this.drawPeaks("gTrace", colors.guanine);
    this.drawPeaks("cTrace", colors.cytosine);
    ctx.closePath();
  };
}