import { call, put, select } from 'redux-saga/effects';
import * as types from '~/store/actionTypes';
import _ from 'lodash';
import { API } from '~/lib/sdk';
import { config } from '~/config';
import { isValidVideo } from '~/lib/validate';
import { analytics } from '~/lib/utils';
import * as selectors from './selectors';
import { resolveCallback, rejectCallback } from './helper';


export function* getAssets(action) {
	try {
		const { options } = action.payload;
		const network = yield select(selectors.network);
		const assets = yield call(API.imagePicker.getAssets, options, network.isConnected);
		const output = assets.map((asset => {
			if (isValidVideo(asset.type)) {
				return {
					...asset,
					startTime: 0,
					endTime: (asset.duration > config.defaultVideoLength)
						? config.defaultVideoLength
						: asset.duration,
				};
			}
			return {
				...asset,
			};
		}));
		if (output.length > 0) {
			analytics.logEvent('select_photos_from_phone', { count: output.length });
			yield put({
				type: types.GET_ASSETS_SUCCESS,
				payload: {
					assets: output,
				},
			});
		}
		if (assets.length > 0) {
			yield call(resolveCallback, action, assets);
		}
	} catch (error) {
		if (error) {
			if (!error.message.toLowerCase().includes('cancel')) {
				yield put({ type: types.SHOW_TOAST_ERROR, payload: { text: error.message } });

				yield put({
					type: types.GET_ASSETS_ERROR,
					payload: { error },
				});
			} else {
				yield put({
					type: types.GET_ASSETS_CANCELLED,
					payload: {},
				});
			}
		}
	}
}

export function* exportAssets(action) {
	try {
		const network = yield select(selectors.network);
		const optimizeUpload = yield select(selectors.optimizeUpload);
		if (_.has(action.payload, 'items')) {
			const responses = yield call(
				API.imagePicker.exportAssets,
				action.payload.items,
				optimizeUpload,
				network.isConnected,
			);
			yield put({
				type: types.EXPORT_ASSETS_SUCCESS,
				payload: {
					exportedAssets: responses,
				},
			});
			yield call(resolveCallback, action, { exportedAssets: responses });
		} else {
			throw new Error('items is can not be null');
		}
	} catch (error) {
		yield call(rejectCallback, action, { error });
		yield put({
			type: types.EXPORT_ASSETS_ERROR,
			payload: { error },
		});
	}
}

export function* cancelExporting() {
	try {
		yield call(API.imagePicker.cancelExporting);
		yield put({
			type: types.EXPORT_ASSETS_ERROR,
			payload: { error: 'export cancelled' },
		});
	} catch (error) {
		yield put({
			type: types.EXPORT_ASSETS_ERROR,
			payload: { error },
		});
	}
}
