import * as FileSystem from "expo-file-system";
import { all, call, put, select, takeLatest } from "redux-saga/effects";
import { handleUpload } from "../../util/document-upload.utility";
import {
  uploadPhotosFailure,
  uploadPhotosSuccess,
  removeAllPhotos,
} from "./photos.actions";
import PhotosActionTypes from "./photos.types";

export function* onRemovePhotos() {
  yield takeLatest(PhotosActionTypes.REMOVE_PHOTOS, removePhotosAction);
}
export function* removePhotosAction({ payload: photoIdsToRemove }) {
  try {
    const photos = yield select((state) => state.photos.photos);
    const fps = photos
      .filter((p) => !photoIdsToRemove.includes(p.id))
      .map((p) => p.uri);

    const all = [];
    fps.forEach((f) => all.push(FileSystem.deleteAsync(f)));

    yield Promise.all(all);
  } catch (error) {
    console.log("Saga Error: removePhotos", error);
  }
}

export function* onRemoveAllPhotos() {
  yield takeLatest(PhotosActionTypes.REMOVE_ALL_PHOTOS, removeAllPhotosAction);
}
export function* removeAllPhotosAction() {
  try {
    //Physically delete all photosSagas.
    const fps = (yield FileSystem.readDirectoryAsync(
      FileSystem.documentDirectory + "photos"
    )).map((f) => {
      return FileSystem.documentDirectory + "photos/" + f;
    });
    const all = [];
    fps.forEach((f) => all.push(FileSystem.deleteAsync(f)));
    yield Promise.all(all);

    console.log("All photos deleted.");
  } catch (error) {
    console.log("Saga Error: onRemoveAllPhotos", error);
  }
}

export function* onUploadAllPhotos() {
  yield takeLatest(
    PhotosActionTypes.UPLOAD_ALL_PHOTOS_START,
    uploadAllPhotosAction
  );
}

export function* uploadAllPhotosAction() {
  try {
    const photos = yield select((state) => state.photos.photos);
    const bodyshop = yield select((state) => state.user.bodyshop);
    const user = yield select((state) => state.user);
    const actions = [];
    photos.forEach(function (p) {
      actions.push(
        call(
          handleUpload,
          ...[
            {
              uri: p.uri,
              onError: handleOnError,
              onProgress: handleOnProgress,
              onSuccess: handleOnSuccess,
            },
            {
              bodyshop: bodyshop,
              jobId: p.jobId,
              uploaded_by: user.currentUser.email,
              photo: p,
            },
          ]
        )
      );
    });
    yield all(actions);
    yield put(removeAllPhotos());
    yield put(uploadPhotosSuccess());
  } catch (error) {
    console.log("Saga Error: uploadAllPhotosAction", error);
    yield put(uploadPhotosFailure(error));
  }
}

function handleOnError(...props) {
  console.log("HandleOnError", props);
}
function handleOnProgress(...props) {
  console.log("HandleOnProgress", props);
}
function handleOnSuccess(...props) {
  console.log("handleOnSuccess", props);
}

export function* photosSagas() {
  yield all([call(onRemoveAllPhotos), call(onUploadAllPhotos)]);
}
