// Copyright © 2022 Olo Inc. All rights reserved.
// This software is made available under the Olo Pay SDK License (See LICENSE.md file)
import useOloPayNativeModule from './useOloPayNativeModule';
import { NativeModules, Platform, findNodeHandle } from 'react-native';
import type { CvvUpdateToken } from '../definitions';

const ViewManager = NativeModules.PaymentCardCvvViewManager;
const AndroidViewManager = useOloPayNativeModule();

const blur = async (ref: any): Promise<void> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.blur(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardCvvViewBlur(nodeHandle);
  }
};

const focus = async (ref: any): Promise<void> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.focus(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardCvvViewFocus(nodeHandle);
  }
};

const clear = async (ref: any): Promise<void> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.clear(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardCvvViewClear(nodeHandle);
  }
};

const createCvvUpdateToken = async (ref: any): Promise<CvvUpdateToken> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.createCvvUpdateToken(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardCvvViewCreateCvvUpdateToken(
      nodeHandle
    );
  }
};

export interface PaymentCardCvvViewNativeMethods {
  blur(ref: any): Promise<void>;
  clear(ref: any): Promise<void>;
  createCvvUpdateToken(ref: any): Promise<CvvUpdateToken>;
  focus(ref: any): Promise<void>;
}

export default function usePaymentCardCvvViewManager(): PaymentCardCvvViewNativeMethods {
  return {
    blur,
    clear,
    createCvvUpdateToken,
    focus,
  };
}
