/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */
import { ADD_PAYMENT_METHOD, UserActionTypes, GET_PAYMENT_METHODS } from "../types/User";
import { ThunkAction } from "redux-thunk";
import { AppReduxState } from "../reducers";
import { Action } from "redux";
import { AsyncStorage } from "react-native";
// import { PaymentMethodForm } from "../../components/paymentsDetails";

export function addPaymentMethod(card: any): ThunkAction<void,AppReduxState,null,Action<string>> {
    return (dispatch, getState) => new Promise(async (resolve,reject)=>{
        const { paymentMethods } = getState().user;
        const { phoneNumber } = getState().auth
        paymentMethods.push(card);
        dispatch(addPaymentMethodDispatch(paymentMethods))
        if(phoneNumber.length){
            await AsyncStorage.setItem('paymentMethods_' + phoneNumber, JSON.stringify(paymentMethods))
        }
        resolve();
    })
  }
  
  function addPaymentMethodDispatch(data:any): UserActionTypes {
    return{
      type: ADD_PAYMENT_METHOD,
      payload: data
    };
  }
  export function getPaymentMethods(): ThunkAction<void,AppReduxState,null,Action<string>> {
    return async (dispatch, getState) => {
        const { phoneNumber } = getState().auth
        if(phoneNumber){
            const paymentMethods = await AsyncStorage.getItem('paymentMethods_' + getState().auth.phoneNumber);
            dispatch(getPaymentMethodsDispatch(paymentMethods ? JSON.parse(paymentMethods) : []));
        }
    }
  }
  
  function getPaymentMethodsDispatch(data:any): UserActionTypes {
    return{
      type: GET_PAYMENT_METHODS,
      payload: data
    };
  }