import React, { Component } from 'react'
import { call, takeLatest, put } from "redux-saga/effects";
import { API_UNI_OIL } from "utils/NotificationApi";
import { setCookie } from "utils/cookie";
import { notification, message } from "antd";

import { apiFormValidation } from 'utils/helper';
const NOTIFICATION_CREATE_REQUEST = "NOTIFICATION_CREATE_REQUEST";
const NOTIFICATION_CREATE_SUCCESS = "NOTIFICATION_CREATE_SUCCESS";
const NOTIFICATION_CREATE_ERROR = "NOTIFICATION_CREATE_ERROR";

function* NotificationSagaFlow({ payload }) {
  const {
    values,
    setSubmitting,
    setErrors,
    history,
    _self
  } = payload;
  try {
    const { data } = yield call(() => API_UNI_OIL.post('notification', { ...values }));
    yield put({ type: NOTIFICATION_CREATE_SUCCESS, payload: data.newNotification });
    message.success('Notification created successfully.'); _self.setState({loading: false})
    history.push({ pathname: '/notifications' });
    
  } catch ({response: error}) {
    notification.error({ 
      message: 'Error', 
      description: <div>
        Something went wrong creating new record.
        { error && error.data && error.data.data && error.data.data.username 
            && (<div>- {error.data.data.username[0]} </div>) }
        { error && error.data && error.data.data && error.data.data.email 
            && (<div>- {error.data.data.email[0]} </div>) }
      </div>,
       duration: 3, 
    });
    yield put({ type: NOTIFICATION_CREATE_ERROR });
    setSubmitting(false); _self.setState({loading: false})

    if (error.status === 422) {
      apiFormValidation({ data: error.data.data, setErrors });
    }
  }
}


function* NotificationCreateSaga() {
  yield takeLatest(NOTIFICATION_CREATE_REQUEST, NotificationSagaFlow);
}
 
export default NotificationCreateSaga;