import { call, put, takeLatest, all} from 'redux-saga/effects';
import * as Api from '../../../services/api';
import * as types from './constants';

export function* getAllAssets(assetType, queryParams) {
  try {
    const result = yield call(Api.getAllAssets, assetType, queryParams);
    yield put({ type: types.GET_ALL_ASSETS_SUCCESS, data: result?.response, isReset: assetType.queryParams.page === 1 });
  } catch (error) {
    yield put({ type: types.GET_ALL_ASSETS_FAILURE, error });
  }
}

export function* uploadAsset(file, assetType, fileParams) {
  try {
    const result = yield call(Api.uploadFile, file, assetType, fileParams);
    yield put({ type: types.UPLOAD_ASSET_SUCCESS, data: result.response.asset, statusCode: result.status ? result.status.code : '' });
  } catch (error) {
    yield put({ type: types.UPLOAD_ASSET_FAILURE, error });
  }
}

export function* deleteAssetById(assetId, assetType) {
  try {
    const result = yield call(Api.deleteAssetById, assetId, assetType);
    
    yield put({ type: types.DELETE_ASSET_SUCCESS, data: result.response });
  } catch (error) {
    yield put({ type: types.DELETE_ASSET_FAILURE, error });
  }
}

export function* fetchUserList() {
  try {
    const result = yield call(Api.getUserList);
    yield put({
        type: types.GET_USER_LIST_SUCCESS,
        data: result.data.result,
      });
  } catch (error) {
    yield put({
        type: types.GET_USER_LIST_FAILURE,
        data: error,
      });
  }
}


function* watchGetAllAssets() {
  yield takeLatest(types.GET_ALL_ASSETS_REQUEST, getAllAssets);
}

function* watchDeleteAssetById() {
  yield takeLatest(types.DELETE_ASSET_REQUEST, deleteAssetById);
}

function* watchUploadAsset() {
  yield takeLatest(types.UPLOAD_ASSET_REQUEST, uploadAsset);
}

function* watchGetUserList() {
  yield takeLatest(types.GET_USER_LIST_REQUEST, fetchUserList);
}

// All sagas to be loaded
export default [
  watchGetAllAssets,
  watchUploadAsset,
  watchDeleteAssetById,
  watchGetUserList,
];


export function* v2GallerySagas() {
  yield all([
    watchGetAllAssets(),
    watchUploadAsset(),
    watchDeleteAssetById(),
    watchGetUserList(),
  ]);
}
