import { useState, useEffect } from 'react';
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';

const LINKING_ERROR =
  `The package 'react-native-bluetooth-message' doesn't seem to be linked. Make sure: \n\n` +
  Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
  '- You rebuilt the app after installing the package\n' +
  '- You are not using Expo managed workflow\n';

const BluetoothMessage = NativeModules.BluetoothMessage
  ? NativeModules.BluetoothMessage
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );

export async function enable(): Promise<String> {
  return BluetoothMessage.enable();
}

export async function discover(): Promise<String> {
  return BluetoothMessage.discover();
}

export async function discoverable(duration: number): Promise<String> {
  return BluetoothMessage.discoverable(duration);
}

export async function connect(deviceAddress: string) {
  return BluetoothMessage.connect(deviceAddress);
}

export async function send(message: string) {
  return BluetoothMessage.send(message);
}

export async function isConnected() {
  return BluetoothMessage.isConnected();
}

export async function disconnect() {
  return BluetoothMessage.disconnect();
}

export function ConnListener(): string {
  const [state, setState] = useState('NOT_CON');
  useEffect(() => {
    const emitter = new NativeEventEmitter(BluetoothMessage);
    const connEmitter = emitter.addListener('conn', (conn: any) => {
      setState(conn.state);
    });

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

  return state;
}

export function DvcListener(): Object[] {
  const [state, setState] = useState<Object[]>([]);
  const [update, setUpdate] = useState<boolean>(false);
  useEffect(() => {
    const emitter = new NativeEventEmitter(BluetoothMessage);
    const dvcEmitter = emitter.addListener('dvc', (dvc) => {
      const tmp = state;
      tmp.push(dvc);
      setState(tmp);
      setUpdate(!update);
    });

    return () => {
      dvcEmitter.remove();
    };
  }, [state, update]);
  return state;
}

export function MsgListener(): string {
  const [state, setState] = useState('NO_MSG');
  useEffect(() => {
    const emitter = new NativeEventEmitter(BluetoothMessage);
    const msg = emitter.addListener('rcvr', (e: any) => {
      setState(e.msg);
    });

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

  return state;
}
