import {
  call, put, takeLatest, all,
} from 'redux-saga/effects';
import * as Api from '../../services/api';
import {
  GET_MARKETING_OBJECTIVES,
  SET_MARKETING_OBJECTIVES_SUCCESS,
  SET_MARKETING_OBJECTIVES_FAILURE,
  UPLOAD_FB_AD_ASSET_REQUEST,
  UPLOAD_FB_AD_ASSET_SUCCESS,
  UPLOAD_FB_AD_ASSET_FAILURE,
  CREATE_FACEBOOK_AD_TEMPLATE_REQUEST,
  CREATE_FACEBOOK_AD_TEMPLATE_SUCCESS,
  CREATE_FACEBOOK_AD_TEMPLATE_FAILURE,
  EDIT_FACEBOOK_AD_TEMPLATE_REQUEST,
  EDIT_FACEBOOK_AD_TEMPLATE_SUCCESS,
  EDIT_FACEBOOK_AD_TEMPLATE_FAILURE,
  GET_FACEBOOK_AD_TEMPLATE_DETAILS_REQUEST,
  GET_FACEBOOK_AD_TEMPLATE_DETAILS_SUCCESS,
  GET_FACEBOOK_AD_TEMPLATE_DETAILS_FAILURE,
  GET_ORG_OU_LIST_FAILURE,
  GET_ORG_OU_LIST_SUCCESS,
  GET_ORG_OU_LIST_REQUEST,
} from './constants';

export function* fetchMarketingObjectives() {
  try {
    const response = yield call(Api.getMarketingObjectives, 'FACEBOOK');
    const { errors, data } = response;
    if (errors && errors.length) {
      yield put({
        type: SET_MARKETING_OBJECTIVES_FAILURE,
        payload: errors,
      });
    } else {
      yield put({
        type: SET_MARKETING_OBJECTIVES_SUCCESS,
        payload: data,
      });
    }
  } catch (error) {
    yield put({
      type: SET_MARKETING_OBJECTIVES_FAILURE,
      payload: error,
    });
  }
}
export function* getOrgOUs({ orgID } = {}) {
  try {
    const apiResponse = yield call(Api.getOrgOUs, { orgID });
    if (apiResponse.status === 200) {
      yield put({
        type: GET_ORG_OU_LIST_SUCCESS,
        payload: apiResponse.result,
      });
    } else {
      yield put({
        type: GET_ORG_OU_LIST_FAILURE,
        payload: apiResponse,
      });
    }
  } catch (error) {
    yield put({
      type: GET_ORG_OU_LIST_FAILURE,
      payload: error,
    });
  }
}

export function* uploadFbAdAsset(file, assetType, fileParams) {
  try {
    const result = yield call(Api.uploadFile, file, assetType, fileParams);
    let videoIdResponse = {};
    if (file.assetType === 'video' && (result.status.code >= 200 && result.status.code < 300)) {
      const {accessToken, actId, pageAccessToken, pageId} = file.videoData;
      videoIdResponse = yield call(Api.getFacebookVideoId, {videoUrl: result.response.asset.metaInfo.secure_file_path, accessToken, actId, pageAccessToken, pageId});
    }
    if (result.status.isError) {
      yield put({ type: UPLOAD_FB_AD_ASSET_FAILURE, error: result.status.message });
    } else if (videoIdResponse.status?.isError) {
      yield put({ type: UPLOAD_FB_AD_ASSET_FAILURE, error: result.status });
    } else {
      yield put({
        type: UPLOAD_FB_AD_ASSET_SUCCESS,
        data: {...result.response.asset, videoIdResponse: videoIdResponse.response},
        statusCode: result.status ? result.status.code : '',
        templateType: file.templateType,
      });
    }
  } catch (error) {
    yield put({ type: UPLOAD_FB_AD_ASSET_FAILURE, error });
  }
}
export function* createFacebookADTemplate({ template, callback }) {
  let errorMsg;
  try {
    const result = yield call(Api.createFacebookADTemplate, { template });
    if (result.status.code >= 400) {
      errorMsg = result.message;
      throw errorMsg;
    }
    yield put({ type: CREATE_FACEBOOK_AD_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg });
    if (callback) {
      callback(result.response);
    }
  } catch (error) {
    yield put({ type: CREATE_FACEBOOK_AD_TEMPLATE_FAILURE, error, errorMsg });
    if (callback) {
      callback(null, errorMsg);
    }
  }
}


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

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


function* watchCreateTemplate() {
  yield takeLatest(CREATE_FACEBOOK_AD_TEMPLATE_REQUEST, createFacebookADTemplate);
  
  
}

function* watchGetTemplateDetails() {
  yield takeLatest(GET_FACEBOOK_AD_TEMPLATE_DETAILS_REQUEST, getTemplateDetails);
  
  
}

function* watchEditTemplate() {
  yield takeLatest(EDIT_FACEBOOK_AD_TEMPLATE_REQUEST, editTemplate);
  
  
}


function* watchFetchMarketingObjective() {
  yield takeLatest(GET_MARKETING_OBJECTIVES, fetchMarketingObjectives);
  
  
}
function* watchUploadFbADAsset() {
  yield takeLatest(UPLOAD_FB_AD_ASSET_REQUEST, uploadFbAdAsset);
  
  
}
export function* watchGetOrgOUs() {
  yield takeLatest(GET_ORG_OU_LIST_REQUEST, getOrgOUs);
}

export default [
  watchFetchMarketingObjective,
  watchUploadFbADAsset,
  watchEditTemplate,
  watchGetTemplateDetails,
  watchCreateTemplate,
  watchGetOrgOUs,
];

export function* v2FacebookSagas() {
  yield all([
    watchFetchMarketingObjective(),
    watchUploadFbADAsset(),
    watchEditTemplate(),
    watchGetTemplateDetails(),
    watchCreateTemplate(),
    watchGetOrgOUs(),
  ]);
}
