import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect, useMemo } from "react";
import useEventCallback from "use-event-callback";
import { styled } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import * as colors from "@material-ui/core/colors";
import Checkbox from "@material-ui/core/Checkbox";
import without from "lodash/without";
import WorkspaceContainer from "../WorkspaceContainer";
var brightColors = [colors.blue[600], colors.green[600], colors.red[600], colors.deepOrange[600], colors.pink[600], colors.teal[600], colors.deepPurple[600], colors.indigo[600], colors.blue[600], colors.cyan[600], colors.purple[600]];
var letters = "abcdefghijklmnopqrstuvwxyz1234567890".split("");

var getRandomColor = function getRandomColor(label) {
  var hashInt = label.id.split("").reduce(function (acc, v, i) {
    return acc + (letters.indexOf(v) + 1);
  }, 0);
  return brightColors[hashInt % brightColors.length];
};

var Container = styled("div")({
  maxWidth: "100vw",
  display: "flex",
  flexDirection: "column"
});
var ImageContainer = styled("div")({
  position: "relative",
  display: "flex",
  flexGrow: 1
});
var Image = styled("img")({
  display: "inline-block",
  position: "absolute",
  left: 0,
  top: 0,
  width: "100%",
  height: "100%",
  objectFit: "contain"
});
var ButtonsContainer = styled("div")({
  paddingLeft: 50,
  paddingRight: 50,
  marginTop: 8,
  textAlign: "center",
  flexShrink: 0
});
var CheckButton = styled(Button)({
  margin: 8,
  color: "#fff",
  fontSize: 18,
  paddingRight: 16,
  transition: "transform 50ms ease"
});
var emptyObj = {},
    emptyArr = [];
export var ImageClassification = function ImageClassification(_ref) {
  var sampleIndex = _ref.sampleIndex,
      iface = _ref.interface,
      sample = _ref.sample,
      _ref$containerProps = _ref.containerProps,
      containerProps = _ref$containerProps === void 0 ? emptyObj : _ref$containerProps,
      onModifySample = _ref.onModifySample;
  var disableHotkeys = containerProps.disableHotkeys;
  if (!iface.labels) throw new Error("No labels defined. Add some labels in Setup to continue.");

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      enlargedLabel = _useState2[0],
      changeEnlargedLabel = _useState2[1];

  var _useState3 = useState(emptyArr),
      _useState4 = _slicedToArray(_useState3, 2),
      currentOutput = _useState4[0],
      changeCurrentOutput = _useState4[1];

  var labels = useMemo(function () {
    return iface.labels.map(function (l) {
      return typeof l === "string" ? {
        id: l,
        description: l
      } : l;
    });
  }, [iface.labels]);
  var onDone = useEventCallback(function (output) {
    onModifySample(_objectSpread(_objectSpread({}, sample), {}, {
      annotation: currentOutput
    }));
    if (containerProps.onExit) containerProps.onExit();
  });
  var onNext = useEventCallback(function () {
    onModifySample(_objectSpread(_objectSpread({}, sample), {}, {
      annotation: currentOutput
    }));
    containerProps.onExit("go-to-next");
  });
  var onPrev = useEventCallback(function () {
    onModifySample(_objectSpread(_objectSpread({}, sample), {}, {
      annotation: currentOutput
    }));
    containerProps.onExit("go-to-previous");
  });
  useEffect(function () {
    var timeout = setTimeout(function () {
      changeEnlargedLabel(null);
    }, 100);
    return function () {
      return clearTimeout(timeout);
    };
  }, [enlargedLabel]);
  var onClickLabel = useEventCallback(function (label) {
    changeEnlargedLabel(label);
    var newOutput;

    if (typeof currentOutput !== "string" && (currentOutput || []).includes(label.id)) {
      newOutput = without(currentOutput, label.id);
    } else {
      if (iface.multiple) {
        newOutput = currentOutput.concat([label.id]);
      } else {
        newOutput = label.id;
      }
    }

    changeCurrentOutput(newOutput);

    if (!iface.multiple && newOutput.length > 0) {
      onModifySample(_objectSpread(_objectSpread({}, sample), {}, {
        annotation: newOutput
      }));
      containerProps.onExit("go-to-next");
    }
  });
  useEffect(function () {
    var newOutput = sample === null || sample === void 0 ? void 0 : sample.annotation;
    if (!newOutput) newOutput = [];
    if (typeof newOutput === "string") newOutput = [newOutput];
    changeCurrentOutput(newOutput);
  }, [sampleIndex, sample]);

  var _useMemo = useMemo(function () {
    if (disableHotkeys) return [{}, {}];
    var hotkeyMap = {
      " ": onNext,
      backspace: onPrev,
      enter: onDone,
      rightarrow: onNext,
      leftarrow: onPrev
    };
    var labelKeyMap = {};

    var _iterator = _createForOfIteratorHelper(labels),
        _step;

    try {
      var _loop = function _loop() {
        var label = _step.value;
        var nextAvailableLetter = label.id.split("").filter(function (l) {
          return letters.includes(l);
        }).find(function (l) {
          return !hotkeyMap[l.toLowerCase()];
        });
        if (!nextAvailableLetter) return "continue";

        hotkeyMap[nextAvailableLetter] = function () {
          return onClickLabel(label);
        };

        labelKeyMap[label.id] = nextAvailableLetter;
      };

      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _ret = _loop();

        if (_ret === "continue") continue;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return [hotkeyMap, labelKeyMap];
  }, [labels, onClickLabel, onDone, onNext, onPrev, disableHotkeys]),
      _useMemo2 = _slicedToArray(_useMemo, 2),
      hotkeyMap = _useMemo2[0],
      labelKeyMap = _useMemo2[1];

  useEffect(function () {
    if (disableHotkeys) return;

    var onKeyDown = function onKeyDown(e) {
      var key = e.key.toLowerCase();

      if (hotkeyMap[key]) {
        hotkeyMap[key]();
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return function () {
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [hotkeyMap, disableHotkeys]);
  return /*#__PURE__*/React.createElement(WorkspaceContainer, Object.assign({}, containerProps, {
    onNext: onNext,
    onPrev: onPrev,
    onRemoveSample: containerProps.onRemoveSample,
    onClickHeaderItem: onDone,
    currentSampleIndex: sampleIndex
  }), /*#__PURE__*/React.createElement(Container, {
    style: {
      height: containerProps.height || "calc(100% - 70px)",
      minHeight: 600
    }
  }, /*#__PURE__*/React.createElement(ImageContainer, null, /*#__PURE__*/React.createElement(Image, {
    src: sample === null || sample === void 0 ? void 0 : sample.imageUrl
  })), /*#__PURE__*/React.createElement(ButtonsContainer, null, labels.map(function (label) {
    return /*#__PURE__*/React.createElement(CheckButton, {
      key: label.id,
      onClick: function onClick() {
        return onClickLabel(label);
      },
      style: {
        backgroundColor: getRandomColor(label),
        transform: enlargedLabel === label ? "scale(1.1,1.1)" : undefined
      }
    }, /*#__PURE__*/React.createElement(Checkbox, {
      style: {
        color: "#fff"
      },
      checked: typeof currentOutput === "object" ? currentOutput.includes(label.id) : currentOutput === label.id
    }), label.id, labelKeyMap[label.id] ? " (".concat(labelKeyMap[label.id], ")") : "");
  }))));
};
export default ImageClassification;