import { NativeModules, NativeEventEmitter, Platform } from 'react-native';
import { Request } from './Request';

const LINKING_ERROR =
  `The package 'react-native-blux' 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 Go\n';

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

export type LogLevel = 'error' | 'verbose';

export type Notification = {
  id: string;
  customerEngagementType: string;
  customerEngagementId: string;
  customerEngagementTaskId: string;
  titile?: string;
  body: string;
  url?: string;
  imageUrl?: string;
  data?: Record<string, any>;
};

class BluxClient {
  static eventEmitter = new NativeEventEmitter(BluxModule);

  // todo : 미래에 필요할 때 사용하여 구현
  // private static setEventHandler(
  //   eventName: string,
  //   callback: (...args: any[]) => any
  // ) {
  //   if (Platform.OS === 'ios') {
  //     this.eventEmitter.removeAllListeners(eventName);
  //     this.eventEmitter.addListener(eventName, callback);
  //   } else {
  //     AppRegistry.registerHeadlessTask(eventName, () => (noti) => {
  //       try {
  //         if (typeof noti.data === 'string') {
  //           noti.data = JSON.parse(noti.data);
  //         }
  //       } catch (e) {
  //         console.error(e);
  //         noti.data = undefined;
  //       }

  //       callback(noti);
  //       return Promise.resolve();
  //     });
  //   }
  // }

  static async initialize(
    bluxClientId: string,
    bluxSecretKey: string,
    requestPermissionOnLaunch: boolean
  ): Promise<void> {
    await BluxModule.initialize(
      bluxClientId,
      bluxSecretKey,
      requestPermissionOnLaunch
    );
  }

  static async setLogLevel(level: LogLevel): Promise<void> {
    await BluxModule.setLogLevel(level);
  }

  static async setUserId(userId: string): Promise<void> {
    await BluxModule.setUserId(userId);
  }

  static async sendRequest(request: Request | Request[]): Promise<void> {
    await BluxModule.sendRequest(
      Array.isArray(request)
        ? request.map((r) => r.getPayload())
        : [request.getPayload()]
    );
  }
}

export default BluxClient;
