import React, { useEffect, useRef } from "react";
import { Keyboard, StyleSheet, View } from "react-native";
import { Platform_Android } from "../commons";
import { tBaseStore } from "../store";

export const Dimensions = () => {
  const refView = useRef<any>();
  const refKeyboard = useRef(false);

  const getDimensions = () => {
    refView.current?.measureInWindow?.(
      (_: number, __: number, w: number, h: number) => {
        refKeyboard.current
          ? tBaseStore.updateKeyboard(tBaseStore.dimens.height - h)
          : tBaseStore.updateDimens({ width: w, height: h });
        refKeyboard.current = false;
      }
    );
  };

  useEffect(() => {
    const onKeyboardShow = Keyboard.addListener(
      Platform_Android ? "keyboardDidShow" : "keyboardWillShow",
      (e) =>
        Platform_Android
          ? (refKeyboard.current = true)
          : tBaseStore.updateKeyboard(e.endCoordinates.height, e.duration)
    );
    const onKeyboardHide = Keyboard.addListener(
      Platform_Android ? "keyboardDidHide" : "keyboardWillHide",
      (e) =>
        Platform_Android
          ? (refKeyboard.current = true)
          : tBaseStore.updateKeyboard(0, e.duration)
    );

    return () => {
      onKeyboardShow.remove();
      onKeyboardHide.remove();
    };
  }, []);

  if (!Platform_Android) return null;

  return (
    <View
      ref={refView}
      style={StyleSheet.absoluteFill}
      onLayout={getDimensions}
    />
  );
};
