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 STATION_CREATE_REQUEST = "STATION_CREATE_REQUEST";
const STATION_CREATE_SUCCESS = "STATION_CREATE_SUCCESS";
const STATION_CREATE_ERROR = "STATION_CREATE_ERROR";

function* stationSagaFlow({ payload }) {
  const {
    values,
    setSubmitting,
    setErrors,
    history,
    _self
  } = payload;
  try {
    const { data } = yield call(() => API_UNI_OIL.post('/stations/add', { ...values })); //username
    console.log({history})
    
    yield put({ type: STATION_CREATE_SUCCESS, payload: data.data });
    message.success('Station created successfully.') && message.success("Don't forget to sync created station to system parameters!"); _self.setState({loading: false})
    history.push({ pathname: '/stations' });
    
  } catch (error) {
    console.log({response: error.response.data.message})
    notification.error({ 
      message: 'Something went wrong creating new record!', 
      description: <div>
        <h3>{error.response.data.message}</h3>
      </div>,
       duration: 4, 
    });
    yield put({ type: STATION_CREATE_ERROR });
    setSubmitting(false); _self.setState({loading: false})

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


function* stationCreateSaga() {
  yield takeLatest(STATION_CREATE_REQUEST, stationSagaFlow);
}
 
export default stationCreateSaga;