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

import { apiFormValidation } from 'utils/helper';
const FUELS_CREATE_REQUEST = "FUELS_CREATE_REQUEST";
const FUELS_CREATE_SUCCESS = "FUELS_CREATE_SUCCESS";
const FUELS_CREATE_ERROR = "FUELS_CREATE_ERROR";

function* FuelCreateSagaFlow({ payload }) {
  const {
    values,
    setSubmitting,
    setErrors,
    history,
    _self
  } = payload;
  try {
    const { data } = yield call(() => API_UNI_OIL.post('/fuels/add', { ...values })); //username
    console.log({history})
    
    yield put({ type: FUELS_CREATE_SUCCESS, payload: data.data });
    message.success('Fuel created successfully.') && message.success("Don't forget to sync created fuel to system parameters!"); _self.setState({loading: false})
    history.push({ pathname: '/fuels' });
    
  } 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: FUELS_CREATE_ERROR });
    setSubmitting(false); _self.setState({loading: false})

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


function* FuelCreateSaga() {
  yield takeLatest(FUELS_CREATE_REQUEST, FuelCreateSagaFlow);
}
 
export default FuelCreateSaga;