
import { creditTreatDemand } from "./IlinkConstants";
import { store } from "../redux/store";
import axios from "axios";
import I18n from 'react-native-i18n'
import { fetchTreatCreditDemandPending, fetchTreatCreditDemandSucsess, fetchTreatCreditDemandError, fetchTreatCreditDemandReset } from "../redux/actions/CreditTreatDemandActions";

export const treatCreditDemand = (idDemand, montant) => {

     let dataToSend = {};

     if (typeof montant !== 'undefined')
          dataToSend = { "montant": montant };

     const auth = store.getState().authKeyReducer;
     const authKey = auth !== null ? `${auth.authKey.token_type} ${auth.authKey.access_token}` : '';

     return dispatch => {
          dispatch(fetchTreatCreditDemandPending());

          axios({
               url: `${creditTreatDemand}/${idDemand}`,
               method: 'PUT',
               headers: {
                    'Authorization': authKey,
                    'X-Localization': I18n.currentLocale()
               },
               data: dataToSend
          })
               .then(response => {
                    console.log(response);
                    dispatch(fetchTreatCreditDemandSucsess(response));
               })
               .catch(error => {
                    if (error.response)
                         dispatch(fetchTreatCreditDemandError(error.response));
                    else if (error.request)
                         dispatch(fetchTreatCreditDemandError(error.request))
                    else
                         dispatch(fetchTreatCreditDemandError(error.message))
               });
     }
}

export const creditDemandResetReducer = () => {
     return dispatch => {
          dispatch(fetchTreatCreditDemandReset());
     }
}