import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useRef } from "react";
import { styled } from "@material-ui/core/styles";
import SimpleDialog from "../SimpleDialog";
import useElectron from "../../hooks/use-electron";
import Select from "react-select";
import downloadYoutubeVideo from "./download-youtube-video";
import Progress from "./progress";
import getYoutubeVideoInformation from "./get-youtube-video-information";
import splitURLsFromTextArea from "./split-urls-from-text-area";
import { useTranslation } from "react-i18next";
var TextArea = styled("textarea")({
  width: "100%",
  minHeight: 300
});
var SelectVideoQualityHeader = styled("h3")({
  lineHeight: 0,
  textAlign: "center"
});
var SelectVideoQuality = styled("div")({
  width: "100%",
  marginBottom: 8,
  paddingBottom: 4
});
var ErrorText = styled("pre")({
  whiteSpace: "pre-wrap",
  color: "#f00"
});
var LoadingText = styled("h2")({
  width: "100%",
  height: "100%",
  margin: "auto auto",
  textAlign: "center"
});
var CompletedVideoTitle = styled("h3")({
  textDecoration: "line-through",
  lineHeight: 0
});
var qualityOptions = [{
  value: "136",
  label: "720p"
}, {
  value: "135",
  label: "480p"
}, {
  value: "lowestvideo",
  label: "Lowest Video Only"
}, // TODO these did not seem to work in a local test (missing video)
// { value: "lowest", label: "lowest" },
// { value: "highest", label: "Highest" },
{
  value: "highestvideo",
  label: "Highest Video Only"
}, {
  value: "lowestaudio",
  label: "Lowest Audio Only"
}, {
  value: "highestaudio",
  label: "Highest Audio Only"
}];

var ImportFromYoutubeUrls = function ImportFromYoutubeUrls(_ref) {
  var open = _ref.open,
      onClose = _ref.onClose,
      onAddSamples = _ref.onAddSamples;

  var _ref2 = useElectron() || {},
      remote = _ref2.remote;

  var _useTranslation = useTranslation(),
      t = _useTranslation.t;

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      urlsFromTextArea = _useState2[0],
      setUrlsFromTextArea = _useState2[1];

  var _useState3 = useState(qualityOptions[0].value),
      _useState4 = _slicedToArray(_useState3, 2),
      videoQuality = _useState4[0],
      setVideoQuality = _useState4[1];

  var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      error = _useState6[0],
      setError = _useState6[1];

  var _useState7 = useState({
    progress: 0
  }),
      _useState8 = _slicedToArray(_useState7, 2),
      unitProgress = _useState8[0],
      setUnitProgress = _useState8[1];

  var _useState9 = useState(0),
      _useState10 = _slicedToArray(_useState9, 2),
      overallProgress = _useState10[0],
      setOverallProgress = _useState10[1];

  var _useState11 = useState(false),
      _useState12 = _slicedToArray(_useState11, 2),
      isDownloading = _useState12[0],
      setIsDownloading = _useState12[1];

  var _useState13 = useState(null),
      _useState14 = _slicedToArray(_useState13, 2),
      completedVideoTitles = _useState14[0],
      setCompletedVideoTitles = _useState14[1];

  var cancelRef = useRef();

  var setDefaultState = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setUnitProgress({
                progress: 0,
                title: ""
              });
              setOverallProgress(0);
              setIsDownloading(false);

            case 3:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function setDefaultState() {
      return _ref3.apply(this, arguments);
    };
  }();

  var closeDialog = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return setDefaultState();

            case 2:
              onClose();

            case 3:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function closeDialog() {
      return _ref4.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/React.createElement(SimpleDialog, {
    open: open,
    onClose: closeDialog,
    title: "Import from Youtube URLs",
    actions: [{
      text: "Cancel Downloads",
      disabled: !isDownloading,
      onClick: function onClick() {
        cancelRef.current();
        setIsDownloading(false);
      }
    }, {
      text: "Download Youtube URLs",
      onClick: function () {
        var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
          var _yield$remote$dialog$, canceled, filePaths, downloadPath, youtubeVideoInfos, completedVideoPaths, completedVideoTitlesArray, youtubeVideosCount, _loop, i;

          return _regeneratorRuntime.wrap(function _callee3$(_context4) {
            while (1) {
              switch (_context4.prev = _context4.next) {
                case 0:
                  setIsDownloading(true);
                  _context4.next = 3;
                  return remote.dialog.showOpenDialog({
                    title: "Directory to download files to",
                    buttonLabel: "Download Files Here",
                    properties: ["createDirectory", "openDirectory", "promptToCreate"]
                  });

                case 3:
                  _yield$remote$dialog$ = _context4.sent;
                  canceled = _yield$remote$dialog$.canceled;
                  filePaths = _yield$remote$dialog$.filePaths;

                  if (!(canceled || !filePaths)) {
                    _context4.next = 8;
                    break;
                  }

                  return _context4.abrupt("return", setIsDownloading(false));

                case 8:
                  downloadPath = filePaths[0];
                  _context4.next = 11;
                  return getYoutubeVideoInformation(remote, urlsFromTextArea, function (_ref5) {
                    var progress = _ref5.progress,
                        text = _ref5.text;
                    setUnitProgress({
                      progress: progress
                    });
                  }).catch(function (errorMessage) {
                    console.error(errorMessage.stack);
                    setError(errorMessage.toString());
                    return null;
                  });

                case 11:
                  youtubeVideoInfos = _context4.sent;

                  if (youtubeVideoInfos) {
                    _context4.next = 14;
                    break;
                  }

                  return _context4.abrupt("return", setIsDownloading(false));

                case 14:
                  completedVideoPaths = [];
                  completedVideoTitlesArray = [];
                  youtubeVideosCount = youtubeVideoInfos.length;
                  _loop = /*#__PURE__*/_regeneratorRuntime.mark(function _loop(i) {
                    var youtubeVideoInfo, videoPath;
                    return _regeneratorRuntime.wrap(function _loop$(_context3) {
                      while (1) {
                        switch (_context3.prev = _context3.next) {
                          case 0:
                            youtubeVideoInfo = youtubeVideoInfos[i];
                            _context3.next = 3;
                            return new Promise(function (resolve, reject) {
                              var _downloadYoutubeVideo = downloadYoutubeVideo({
                                remote: remote,
                                downloadPath: downloadPath,
                                youtubeUrl: youtubeVideoInfo.url,
                                title: youtubeVideoInfo.title,
                                videoQuality: videoQuality,
                                onChangeOverallProgress: function onChangeOverallProgress(currentProgress) {
                                  return setOverallProgress((completedVideoTitlesArray.length * 100 + currentProgress) / (youtubeVideosCount * 100) * 100);
                                },
                                onProgress: function onProgress(_ref6) {
                                  var progress = _ref6.progress,
                                      text = _ref6.text;
                                  return setUnitProgress({
                                    progress: progress,
                                    title: youtubeVideoInfo.title,
                                    progressText: text
                                  });
                                },
                                onComplete: function onComplete(filePath) {
                                  return resolve(filePath);
                                }
                              }),
                                  cancel = _downloadYoutubeVideo.cancel;

                              cancelRef.current = cancel;
                            });

                          case 3:
                            videoPath = _context3.sent;
                            completedVideoTitlesArray.push( /*#__PURE__*/React.createElement("li", {
                              key: i + youtubeVideoInfo.title
                            }, /*#__PURE__*/React.createElement(CompletedVideoTitle, null, youtubeVideoInfo.title)));
                            setCompletedVideoTitles(completedVideoTitlesArray);
                            completedVideoPaths.push(videoPath);

                          case 7:
                          case "end":
                            return _context3.stop();
                        }
                      }
                    }, _loop);
                  });
                  i = 0;

                case 19:
                  if (!(i < youtubeVideosCount)) {
                    _context4.next = 24;
                    break;
                  }

                  return _context4.delegateYield(_loop(i), "t0", 21);

                case 21:
                  i++;
                  _context4.next = 19;
                  break;

                case 24:
                  onAddSamples(completedVideoPaths.map(function (videoPath) {
                    return {
                      videoUrl: "file://".concat(videoPath)
                    };
                  }));
                  setIsDownloading(false);

                case 26:
                case "end":
                  return _context4.stop();
              }
            }
          }, _callee3);
        }));

        function onClick() {
          return _onClick.apply(this, arguments);
        }

        return onClick;
      }(),
      disabled: isDownloading
    }]
  }, error && /*#__PURE__*/React.createElement(ErrorText, null, error), isDownloading && (unitProgress && unitProgress.progress && unitProgress.progress > 0 || completedVideoTitles && Array.isArray(completedVideoTitles) === true && completedVideoTitles.length > 0) ? /*#__PURE__*/React.createElement(Progress, {
    unitProgress: unitProgress,
    completedVideoTitles: completedVideoTitles,
    overallProgress: overallProgress
  }) : isDownloading === true ? /*#__PURE__*/React.createElement(LoadingText, null, "Information is Loading") : null, !isDownloading && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(SelectVideoQuality, null, /*#__PURE__*/React.createElement(SelectVideoQualityHeader, null, t("select-video-quality")), /*#__PURE__*/React.createElement(Select, {
    defaultValue: qualityOptions[0],
    options: qualityOptions,
    onChange: function onChange(_ref7) {
      var value = _ref7.value;
      return setVideoQuality(value);
    }
  })), /*#__PURE__*/React.createElement(TextArea, {
    onChange: function onChange(e, v) {
      setUrlsFromTextArea(splitURLsFromTextArea(e.target.value));
    },
    placeholder: "Paste Youtube URLs here\nOne URL per line"
  })));
};

export default ImportFromYoutubeUrls;