import * as Device from "expo-device";
import { BluetoothDevice } from "react-native-bluetooth-classic";
import { printReceipt } from "react-native-nexgo";
import Pax from "react-native-pax-library";

export function usePrinter() {
  const isPaxDevice = Device.modelName === "A920Pro";
  const isNexGoDevice = Device.modelName === "N86";

  async function printWithNexGo(data: string) {
    try {
      await printReceipt({ data: data });
      return true;
    } catch (error) {
      console.log(error);
      return false;
    }
  }
  async function printWithPax(data: string) {
    try {
      Pax.printStr(data, Pax.PARTIAL_CUT);
      return true;
    } catch (error) {
      console.error(error);
      return false;
    }
  }

  async function printWithBluetooth(
    device: BluetoothDevice,
    data: string
  ) {
    try {
      if (await device.isConnected()) {
        return await device.write(data + "\n");
      }
      const connected = await device.connect();
      if (connected) {
        return await device.write(data + "\n");
      }

      throw new Error("Could not connect to device");
    } catch (e) {
      console.error(e);
      return false;
    }
  }

  return {
    printWithBluetooth,
    printWithPax,
    printWithNexGo,
    isPaxDevice,
    isNexGoDevice,
  };
}
