"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.startLoading = startLoading;
exports.stopLoading = stopLoading;
exports.receiveFolder = receiveFolder;
exports.failFoldersLoad = failFoldersLoad;
exports.startUpload = startUpload;
exports.failUpload = failUpload;
exports.quotaExceeded = quotaExceeded;
exports.completeUpload = completeUpload;
exports.openOrCloseUploadForm = openOrCloseUploadForm;
exports.processedFolderBatch = processedFolderBatch;
exports.allUploadCompleteActions = allUploadCompleteActions;
exports.embedUploadResult = embedUploadResult;
exports.fetchFolders = fetchFolders;
exports.setUsageRights = setUsageRights;
exports.getFileUrlIfMissing = getFileUrlIfMissing;
exports.generateThumbnailUrl = generateThumbnailUrl;
exports.setAltText = setAltText;
exports.handleFailures = handleFailures;
exports.uploadPreflight = uploadPreflight;
exports.STOP_LOADING = exports.START_LOADING = exports.QUOTA_EXCEEDED_UPLOAD = exports.PROCESSED_FOLDER_BATCH = exports.TOGGLE_UPLOAD_FORM = exports.COMPLETE_FILE_UPLOAD = exports.FAIL_FILE_UPLOAD = exports.START_FILE_UPLOAD = exports.FAIL_FOLDERS_LOAD = exports.RECEIVE_FOLDER = void 0;

var files = _interopRequireWildcard(require("./files"));

var images = _interopRequireWildcard(require("./images"));

var _bridge = _interopRequireDefault(require("../../bridge"));

var _mimeClass = require("../../common/mimeClass");

/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */
var RECEIVE_FOLDER = "RECEIVE_FOLDER";
exports.RECEIVE_FOLDER = "RECEIVE_FOLDER";
var FAIL_FOLDERS_LOAD = "FAIL_FOLDERS_LOAD";
exports.FAIL_FOLDERS_LOAD = "FAIL_FOLDERS_LOAD";
var START_FILE_UPLOAD = "START_FILE_UPLOAD";
exports.START_FILE_UPLOAD = "START_FILE_UPLOAD";
var FAIL_FILE_UPLOAD = "FAIL_FILE_UPLOAD";
exports.FAIL_FILE_UPLOAD = "FAIL_FILE_UPLOAD";
var COMPLETE_FILE_UPLOAD = "COMPLETE_FILE_UPLOAD";
exports.COMPLETE_FILE_UPLOAD = "COMPLETE_FILE_UPLOAD";
var TOGGLE_UPLOAD_FORM = "TOGGLE_UPLOAD_FORM";
exports.TOGGLE_UPLOAD_FORM = "TOGGLE_UPLOAD_FORM";
var PROCESSED_FOLDER_BATCH = "PROCESSED_FOLDER_BATCH";
exports.PROCESSED_FOLDER_BATCH = "PROCESSED_FOLDER_BATCH";
var QUOTA_EXCEEDED_UPLOAD = "QUOTA_EXCEEDED_UPLOAD";
exports.QUOTA_EXCEEDED_UPLOAD = "QUOTA_EXCEEDED_UPLOAD";
var START_LOADING = "START_LOADING";
exports.START_LOADING = "START_LOADING";
var STOP_LOADING = "STOP_LOADING";
exports.STOP_LOADING = "STOP_LOADING";

function startLoading() {
  return {
    type: START_LOADING
  };
}

function stopLoading() {
  return {
    type: STOP_LOADING
  };
}

function receiveFolder(_ref) {
  var id = _ref.id,
      name = _ref.name,
      parentId = _ref.parentId;
  return {
    type: RECEIVE_FOLDER,
    id: id,
    name: name,
    parentId: parentId
  };
}

function failFoldersLoad(error) {
  return {
    type: FAIL_FOLDERS_LOAD,
    error: error
  };
}

function startUpload(fileMetaProps) {
  return {
    type: START_FILE_UPLOAD,
    file: fileMetaProps
  };
}

function failUpload(error) {
  return {
    type: FAIL_FILE_UPLOAD,
    error: error
  };
}

function quotaExceeded(error) {
  return {
    type: QUOTA_EXCEEDED_UPLOAD,
    error: error
  };
}

function completeUpload(results) {
  return {
    type: COMPLETE_FILE_UPLOAD,
    results: results
  };
}

function openOrCloseUploadForm() {
  return {
    type: TOGGLE_UPLOAD_FORM
  };
}

function processedFolderBatch(_ref2) {
  var folders = _ref2.folders;
  return {
    type: PROCESSED_FOLDER_BATCH,
    folders: folders
  };
}

function allUploadCompleteActions(results, fileMetaProps) {
  var actions = [];
  actions.push(completeUpload(results));
  var fileProps = {
    id: results.id,
    name: results.display_name,
    url: results.preview_url,
    type: fileMetaProps.contentType,
    embed: (0, _mimeClass.fileEmbed)(results)
  };
  actions.push(files.createAddFile(fileProps));
  actions.push(files.createInsertFile(fileMetaProps.parentFolderId, results.id));

  if (/^image\//.test(results["content-type"])) {
    actions.push(images.createAddImage(results));
  }

  return actions;
}

function embedUploadResult(results, selectedTabType) {
  var embedData = (0, _mimeClass.fileEmbed)(results);

  if (selectedTabType == "images" && embedData.type == "image" && !(_bridge.default.existingContentToLink() && !_bridge.default.existingContentToLinkIsImg())) {
    _bridge.default.insertImage(results);
  } else {
    _bridge.default.insertLink({
      title: results.display_name,
      href: results.url,
      embed: embedData
    });
  }

  return results;
} // fetches the list of folders to select from when uploading a file


function fetchFolders(bookmark) {
  return function (dispatch, getState) {
    dispatch(startLoading());

    var _getState = getState(),
        source = _getState.source,
        jwt = _getState.jwt,
        upload = _getState.upload,
        host = _getState.host,
        contextId = _getState.contextId,
        contextType = _getState.contextType;

    if (bookmark || upload.folders && Object.keys(upload.folders).length === 0) {
      return source.fetchFolders({
        jwt: jwt,
        host: host,
        contextId: contextId,
        contextType: contextType
      }, bookmark).then(function (_ref3) {
        var folders = _ref3.folders,
            bookmark = _ref3.bookmark;
        dispatch(folders.map(receiveFolder));

        var _getState2 = getState(),
            upload = _getState2.upload;

        dispatch(processedFolderBatch(upload));

        if (bookmark) {
          dispatch(fetchFolders(bookmark));
        } else {
          dispatch(stopLoading());
        }
      }).catch(function (error) {
        dispatch(failFoldersLoad(error));
      });
    }
  };
}

function setUsageRights(source, fileMetaProps, results) {
  var usageRights = fileMetaProps.usageRights;

  if (usageRights) {
    source.setUsageRights(results.id, usageRights);
  }

  return results;
}

function getFileUrlIfMissing(source, results) {
  if (results.url) {
    return Promise.resolve(results);
  }

  return source.getFile(results.id).then(function (file) {
    results.url = file.url;
    return results;
  });
}

function readUploadedFileAsDataURL(file) {
  var reader = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new FileReader();
  return new Promise(function (resolve, reject) {
    reader.onerror = function () {
      reader.abort();
      reject(new DOMException("Unable to parse file"));
    };

    reader.onload = function () {
      resolve(reader.result);
    };

    reader.readAsDataURL(file);
  });
}

function generateThumbnailUrl(results, fileDOMObject, reader) {
  if (/^image\//.test(results["content-type"])) {
    return readUploadedFileAsDataURL(fileDOMObject, reader).then(function (result) {
      results.thumbnail_url = result;
      return results;
    });
  } else {
    return Promise.resolve(results);
  }
}

function setAltText(altText, results) {
  if (altText) {
    results.alt_text = altText;
  }

  return results;
}

function handleFailures(error, dispatch) {
  return error.response.json().then(function (resp) {
    if (resp.message === "file size exceeds quota") {
      dispatch(quotaExceeded(error));
    } else {
      dispatch(failUpload(error));
    }
  }).catch(function (error) {
    return dispatch(failUpload(error));
  });
}

function uploadPreflight(tabContext, fileMetaProps) {
  return function (dispatch, getState) {
    var _getState3 = getState(),
        source = _getState3.source,
        jwt = _getState3.jwt,
        host = _getState3.host,
        contextId = _getState3.contextId,
        contextType = _getState3.contextType;

    var fileReader = fileMetaProps.fileReader;
    dispatch(startUpload(fileMetaProps));
    return source.preflightUpload(fileMetaProps, {
      jwt: jwt,
      host: host,
      contextId: contextId,
      contextType: contextType
    }).then(function (results) {
      return source.uploadFRD(fileMetaProps.domObject, results);
    }).then(function (results) {
      return setUsageRights(source, fileMetaProps, results);
    }).then(function (results) {
      return getFileUrlIfMissing(source, results);
    }).then(function (results) {
      return generateThumbnailUrl(results, fileMetaProps.domObject, fileReader);
    }).then(function (results) {
      return setAltText(fileMetaProps.altText, results);
    }).then(function (results) {
      return embedUploadResult(results, tabContext);
    }).then(function (results) {
      dispatch(allUploadCompleteActions(results, fileMetaProps));
    }).catch(function (err) {
      return handleFailures(err, dispatch);
    });
  };
}