import mime from "mime-types";
import { Storage } from "aws-amplify";
import { getUrl, generateImageName, randomString } from "../helper";
import { authedFunction } from "../session";
import Config from "../config";

export const fileActions = {
	getUploadUrl: (userId, fileName) => {
		const newFilename = fileName.replace(/[^a-z0-9+.]+/gi, "").toLowerCase();
		return `uploads/users/${userId}/public/${randomString()}/${newFilename}`;
	},
	uploadUserMediaWithProgress: async (
		imageUri,
		url,
		progressCallback = null,
	) => {
		const blob = await fileActions.imageToBlob(imageUri);
		return fileActions.uploadBlobAWS(
			Config.env.awsUploadsBucket,
			url,
			blob,
			"",
			progressCallback,
		);
	},
	// uploadUserMedia: async (userId, image, fileName) => {
	//   const blob = await fileActions.imageToBlob(image.uri);
	//   const url = fileActions.getUploadUrl(userId, fileName);
	//   return fileActions.uploadBlobAWS(Config.env.awsUploadsBucket, url, blob);
	// },
	// uploadSignatureImage: async (image, name) => {
	//   const blob = await fileActions.imageToBlob(image);
	//   const newImageName = generateImageName(name, 'signature.png');
	//   return fileActions.uploadBlobAWS(Config.env.awsStorageBucket, newImageName, blob, 'images/');
	// },
	imageToBlob: async (imageUri) => {
		const response = await fetch(imageUri);
		return response.blob();
	},
	uploadBlobAWS: (bucket, uri, blob, prefix = "", progressCallback = null) => {
		const imageName = prefix ? uri.replace(/^.*[\\/]/, "") : uri;
		const fileType = mime.lookup(uri);
		const access = {
			level: "public",
			bucket,
			contentType: fileType,
			customPrefix: { public: "" },
			progressCallback: (progress) =>
				progressCallback &&
				progressCallback({
					uri,
					loaded: progress.loaded,
					total: progress.total,
					percentage: `${Math.floor((progress.loaded / progress.total) * 100)}%`,
				}),
		};
		return Storage.put(`${prefix}${imageName}`, blob, access);
	},
	getStockPhotos: async () => {
		const response = await authedFunction({
			method: "GET",
			url: "https://pluss60.pluss60-api.com/media-demo/library",
		});
		// Convert to images object
		const images = response.data.map((image) => {
			return { uri: image };
		});
		return images;
	},
	getMediaFolders: (site) => {
		const query = { site };
		return authedFunction({
			method: "GET",
			url: getUrl("media", "folders", query),
		});
	},
	// addMediaFolder: (site, name, images) => {
	//   return authedFunction({
	//     method: 'POST',
	//     url: getUrl('media', 'addFolder'),
	//     data: {
	//       site,
	//       name,
	//       images,
	//     },
	//   });
	// },
	// addImagesToFolder: (id, site, images) => {
	//   return authedFunction({
	//     method: 'POST',
	//     url: getUrl('media', 'addImages'),
	//     data: {
	//       id,
	//       site,
	//       images,
	//     },
	//   });
	// },
};
