/**
 * 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 { ThunkAction } from "redux-thunk";
import { AppReduxState } from "../reducers";
import { Action } from "redux";
import { HomeActionTypes, GET_PHONE_NUMBER, SET_VERIFICATION_CODE, LOGIN_USER } from "../types/Authentication";
import { AsyncStorage } from "react-native";

export function getPhoneNumber(param:string): ThunkAction<void,AppReduxState,null,Action<string>> {
    return dispatch => {
      dispatch(getPhoneNumberDispatch(param))
    }
  }
  
  function getPhoneNumberDispatch(data: string):HomeActionTypes {
    return {
      type: GET_PHONE_NUMBER,
      payload: data
    };
}

export function genrateVerificationCode(): ThunkAction<void,AppReduxState,null,Action<string>> {
  return dispatch => {
    const code = Math.floor(100000 + Math.random() * 900000).toString()
    dispatch(genrateVerificationCodeDispatch(code))
  }
}

function genrateVerificationCodeDispatch(data: string):HomeActionTypes {
  return {
    type: SET_VERIFICATION_CODE,
    payload: data
  };
}

export function loginUser(userNumber:string): ThunkAction<void,AppReduxState,null,Action<string>> {
  return async dispatch => {
    await AsyncStorage.setItem('userNumber', userNumber);
    dispatch(setUserDispatch(true))
  }
}

export function logoutUser(): ThunkAction<void,AppReduxState,null,Action<string>> {
  return async dispatch => {
    await AsyncStorage.removeItem('userNumber');
    dispatch(setUserDispatch(false))
  }
}

export function checkUser(): ThunkAction<void,AppReduxState,null,Action<string>> {
  return dispatch => new Promise(async (resolve) => {
    const userNumber = await AsyncStorage.getItem('userNumber');
    if(userNumber){
      dispatch(setUserDispatch(true))
      dispatch(getPhoneNumberDispatch(userNumber))
      resolve({userLoggedIn: true})
    } else {
      dispatch(setUserDispatch(false))
      resolve({userLoggedIn: false})
    }
  })
}

function setUserDispatch(data?: boolean):HomeActionTypes {
  return {
    type: LOGIN_USER,
    payload: data
  };
}