import {
  call, put, takeLatest, all,
} from 'redux-saga/effects';
import * as Api from '../../services/api';
import { pollAssetStatus } from '../../sagas/assetPolling';
import { createPollingConfig } from '../../utils/asyncAssetUpload';
import { ASSET_STATUS } from '../../utils/assetStatusConstants';
import * as types from './constants';
import messages from './messages';

export function* uploadViberAsset(params) {
  try {
    const result = yield call(Api.uploadFile, params);
    const responseData = result?.response || {};
    const statusCode = result?.status?.code || result?.statusCode;
    const asset = responseData?.asset || responseData;

    if (statusCode === 202 || responseData?.processingStatus === ASSET_STATUS.PROCESSING) {
      const assetId = asset?._id || responseData?.assetId;
      const { templateType } = params || {};
      const assetType = params?.assetType || asset?.type?.toLowerCase() || 'image';

      if (assetId) {
        yield put({
          type: types.UPLOAD_VIBER_ASSET_PROCESSING,
          payload: {
            assetId,
            asset,
            processingStatus: ASSET_STATUS.PROCESSING,
          },
        });

        const actionTypes = {
          COMPLETED: types.UPLOAD_VIBER_ASSET_COMPLETED,
          FAILED: types.UPLOAD_VIBER_ASSET_FAILED,
          TIMEOUT: types.UPLOAD_VIBER_ASSET_TIMEOUT,
        };
        const pollingConfig = createPollingConfig(assetType, assetId, actionTypes, templateType);
        yield call(pollAssetStatus, pollingConfig);
      } else {
        yield put({
          type: types.UPLOAD_VIBER_ASSET_FAILED,
          payload: {
            assetId: undefined,
            error: messages.assetIdMissingError,
          },
          templateType,
        });
      }
    } else {
      yield put({
        type: types.UPLOAD_VIBER_ASSET_SUCCESS,
        data: asset,
        statusCode,
        templateType: params?.templateType,
      });
    }
  } catch (error) {
    yield put({ type: types.UPLOAD_VIBER_ASSET_FAILURE, error });
  }
}

export function* createViberTemplate({ template, callback }) {
  let errorMsg;
  try {
    const result = yield call(Api.createViberTemplate, { template });
    if (result.status.code >= 400) {
      errorMsg = result.message;
      throw errorMsg;
    }
    yield put({ type: types.CREATE_VIBER_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg });
    if (callback) {
      callback(result.response);
    }
  } catch (error) {
    yield put({ type: types.CREATE_VIBER_TEMPLATE_FAILURE, error, errorMsg });
    if (callback) {
      callback(null, errorMsg);
    }
  }
}


export function* editTemplate({ template, callback }) {
  let errorMsg;
  try {
    const result = yield call(Api.createViberTemplate, {template});
    if (result.status.code >= 400) {
      errorMsg = result.message;
      throw errorMsg;
    }
    if (callback) {
      callback(result.response);
    }
    yield put({ type: types.EDIT_VIBER_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg });
  } catch (error) {
    yield put({ type: types.EDIT_VIBER_TEMPLATE_FAILURE, error, errorMsg });
    if (callback) {
      callback(null, errorMsg);
    }
  }
}

export function* getTemplateDetails({id, callback}) {
  try {
    
    const result = yield call(Api.getTemplateDetails, {id, channel: 'VIBER'});
    yield put({ type: types.GET_VIBER_TEMPLATE_DETAILS_SUCCESS, data: result.response });
    if (callback) {
      callback(false);
    }
  } catch (error) {
    yield put({ type: types.GET_VIBER_TEMPLATE_DETAILS_FAILURE, error });
  }
}


function* watchUploadViberAsset() {
  yield takeLatest(types.UPLOAD_VIBER_ASSET_REQUEST, uploadViberAsset);
  
  
}


function* watchCreateTemplate() {
  
  yield takeLatest(types.CREATE_VIBER_TEMPLATE_REQUEST, createViberTemplate);
  
  
}

function* watchGetTemplateDetails() {
  yield takeLatest(types.GET_VIBER_TEMPLATE_DETAILS_REQUEST, getTemplateDetails);
  
  
}

function* watchEditTemplate() {
  yield takeLatest(types.EDIT_VIBER_TEMPLATE_REQUEST, editTemplate);
  
  
}

export default [
  watchUploadViberAsset,
  watchCreateTemplate,
  watchGetTemplateDetails,
  watchEditTemplate,
];

export function* v2ViberSagas() {
  yield all([
    watchUploadViberAsset(),
    watchCreateTemplate(),
    watchGetTemplateDetails(),
    watchEditTemplate(),
  ]);
}