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 BRANCHES_CREATE_REQUEST = "BRANCHES_CREATE_REQUEST";
const BRANCHES_CREATE_SUCCESS = "BRANCHES_CREATE_SUCCESS";
const BRANCHES_CREATE_ERROR = "BRANCHES_CREATE_ERROR";

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

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


function* BranchCreateSaga() {
  yield takeLatest(BRANCHES_CREATE_REQUEST, BranchSagaFlow);
}
 
export default BranchCreateSaga;