import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect, useCallback } from "react";
import SimpleDialog from "../SimpleDialog";
import Button from "@material-ui/core/Button";
import { styled } from "@material-ui/core/styles";
import { useTranslation } from "react-i18next";
var ExplainText = styled("div")({
  marginTop: 8,
  marginBottom: 8
});
var GoogleDriveScreenshot = styled("img")({
  width: "100%",
  boxSizing: "border-box"
}); // Example for Google OAuth
// https://developers.google.com/drive/api/v3/picker

var credentials = {
  web: {
    client_id: process.env.REACT_APP_GOOGLE_DRIVE_CLIENT_ID || "294393711342-h5aqqt3pvn8othepvsmi16iakdhi7m6j.apps.googleusercontent.com",
    app_id: process.env.REACT_APP_GOOGLE_DRIVE_APP_ID || "294393711342",
    developer_key: process.env.REACT_APP_GOOGLE_DRIVE_DEVELOPER_KEY || "AIzaSyCoNoDnfzDBSXpt84Q75LU9UMTzvyLkRhg"
  }
};
var scope = "https://www.googleapis.com/auth/drive.readonly";
export default (function (_ref) {
  var open = _ref.open,
      onClose = _ref.onClose,
      onAddSamples = _ref.onAddSamples;

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

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      googleScriptLoaded = _useState2[0],
      setGoogleScriptLoaded = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      pickerApiLoaded = _useState4[0],
      setPickerApiLoaded = _useState4[1];

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

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      userSelectedItemsFromDrive = _useState8[0],
      setUserSelectedItemsFromDrive = _useState8[1];

  var _useState9 = useState(false),
      _useState10 = _slicedToArray(_useState9, 2),
      isPickerOpen = _useState10[0],
      setIsPickerOpen = _useState10[1];

  useEffect(function () {
    var scriptElement = document.createElement("script");
    scriptElement.src = "https://apis.google.com/js/api.js";
    scriptElement.async = true;

    scriptElement.onload = function () {
      setGoogleScriptLoaded(true);
    };

    document.body.appendChild(scriptElement);
    return function () {
      scriptElement.remove();
    };
  }, []);
  var googlePickerActionCallback = useCallback(function (data) {
    if (data.action === window.google.picker.Action.PICKED) {
      setUserSelectedItemsFromDrive(data.docs.map(function (googleDriveDocument) {
        return {
          url: googleDriveDocument.url,
          mimeType: googleDriveDocument.mimeType,
          name: googleDriveDocument.name,
          id: googleDriveDocument.id
        };
      }));
      setIsPickerOpen(false);
    } else if (data.action === "cancel") {
      onClose();
    }
  }, [onClose]);
  var createPicker = useCallback(function () {
    if (pickerApiLoaded && oauthToken) {
      var view = new window.google.picker.DocsView(window.google.picker.ViewId.Docs, window.google.picker.ViewId.FOLDERS).setIncludeFolders(true).setSelectFolderEnabled(true);
      var picker = new window.google.picker.PickerBuilder().enableFeature(window.google.picker.Feature.NAV_HIDDEN).enableFeature(window.google.picker.Feature.MINE_ONLY).enableFeature(window.google.picker.Feature.MULTISELECT_ENABLED).setAppId(credentials.web.app_id).setOAuthToken(oauthToken).addView(view).addView(window.google.picker.ViewId.DOCS).setDeveloperKey(credentials.web.developer_key).setCallback(googlePickerActionCallback).build();
      picker.setVisible(true);
      setIsPickerOpen(true);
    }
  }, [googlePickerActionCallback, oauthToken, pickerApiLoaded]);
  useEffect(function () {
    createPicker();
  }, [pickerApiLoaded, oauthToken, createPicker]);
  var handleAuthenticationResponse = useCallback(function (authenticationResponse) {
    if (authenticationResponse && !authenticationResponse.error) {
      setOAuthToken(authenticationResponse.access_token);
      createPicker();
    }
  }, [createPicker]);
  var onAuthApiLoad = useCallback(function () {
    window.gapi.auth.authorize({
      client_id: credentials.web.client_id,
      scope: scope,
      immediate: false
    }, handleAuthenticationResponse);
  }, [handleAuthenticationResponse]);
  var onPickerApiLoad = useCallback(function () {
    setPickerApiLoaded(true);
    createPicker();
  }, [createPicker]);
  var onLoadPicker = useCallback(function () {
    if (googleScriptLoaded === true) {
      window.gapi.load("auth", {
        callback: onAuthApiLoad
      });
      window.gapi.load("picker", {
        callback: onPickerApiLoad
      });
    }
  }, [googleScriptLoaded, onAuthApiLoad, onPickerApiLoad]);

  var onAddSamplesClicked = function onAddSamplesClicked() {
    var samples = [];

    var _iterator = _createForOfIteratorHelper(userSelectedItemsFromDrive),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var item = _step.value;

        if (item.mimeType.includes("image/")) {
          samples.push({
            imageUrl: "https://drive.google.com/uc?id=".concat(item.id)
          });
        } else if (item.mimeType.includes("video/")) {
          samples.push({
            videoUrl: "https://drive.google.com/uc?id=".concat(item.id)
          });
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    onAddSamples(samples);
  };

  useEffect(function () {
    if (open) {
      onLoadPicker();
    }
  }, [open, googleScriptLoaded, onLoadPicker]);
  return /*#__PURE__*/React.createElement(SimpleDialog, {
    open: open && !isPickerOpen,
    onClose: onClose,
    title: "Import from Google Drive",
    actions: [userSelectedItemsFromDrive && userSelectedItemsFromDrive.length > 0 && {
      text: "Add ".concat(userSelectedItemsFromDrive.length, " Samples"),
      onClick: onAddSamplesClicked
    }].filter(Boolean)
  }, /*#__PURE__*/React.createElement(Button, {
    variant: "outlined",
    onClick: onLoadPicker
  }, t("reopen-google-drive-picker")), /*#__PURE__*/React.createElement(ExplainText, null, t("import-from-google-drive-explanation-text"), ".", " ", /*#__PURE__*/React.createElement("b", null, t("import-from-google-drive-explanation-bold-text"), "!")), /*#__PURE__*/React.createElement(GoogleDriveScreenshot, {
    src: "https://s3.amazonaws.com/asset.workaround.online/google-share-screenshot.png"
  }));
});