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_UPDATE_REQUEST = "STATION_UPDATE_REQUEST";
const STATION_UPDATE_SUCCESS = "STATION_UPDATE_SUCCESS";
const STATION_UPDATE_ERROR = "STATION_UPDATE_ERROR";

function* stationUpdateSagaFlow({ payload }) {
  const {
    id,
    values,
    setSubmitting,
    setErrors,
    history,
    _self
  } = payload;
  try {
    const { data } = yield call(() => API_UNI_OIL.put(`/stations/${id}`, { ...values })); //username
    console.log({history})
    
    yield put({ type: STATION_UPDATE_SUCCESS, payload: data.data });
    message.success('Station updated successfully.') && message.success("Don't forget to sync updated station to system parameters!"); _self.setState({loading: false})
    history.push({ pathname: '/stations' });
    
  } catch (error) {
    console.log(error.response.data.message)
    notification.error({ 
      message: 'Something went wrong updating record!', 
      description: <div>
        <h3>{error.response.data.message}</h3>
      </div>,
       duration: 3, 
    });
    yield put({ type: STATION_UPDATE_ERROR });
    setSubmitting(false); _self.setState({loading: false})

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


function* stationUpdateSaga() {
  yield takeLatest(STATION_UPDATE_REQUEST, stationUpdateSagaFlow);
}
 
export default stationUpdateSaga;