import React, { Component } from 'react';
import { Platform, requireNativeComponent } from 'react-native';
import type { ViewProps } from 'react-native';
import TRTCCloud, { TRTCCloudDef } from 'trtc-react-native';

export interface TXVideoViewProps {
  userId: string;
  viewType?: number;
  streamType: number;
  mirror?: boolean;
  frontCamera?: boolean;
}

interface TXRenderViewProps {
  data: { userId: string; streamType: number; frontCamera?: boolean;};
}

interface TRTCRenderParams {
  renderParams?: {
    rotation: number;
    fillMode: number;
    mirrorType: number;
    streamType: number;
    userId: string;
  };
}

/**
 * @ignore
 */
const TXSurfaceView = requireNativeComponent<
  TXRenderViewProps & TRTCRenderParams
>('TXVideoView');

/**
 * @ignore
 */
export class RtcVideoView extends Component<ViewProps & TXVideoViewProps, {}> {
  componentWillUnmount() {
    const { userId, streamType} = this.props;
    const trtcCloud = TRTCCloud.sharedInstance();
    if (userId === "") {
      trtcCloud.stopLocalPreview();
    } else {
      trtcCloud.stopRemoteView(userId, streamType);
    }
  }

  render() {
    const { viewType, userId, streamType, frontCamera, ...otherProps } = this.props;
    // @ts-ignore
    let renderParams = this.props.renderParams;
    if (renderParams) {
      if (!renderParams.fillMode) {
        renderParams.fillMode = TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;
      }
      if (!renderParams.rotation) {
        renderParams.rotation = TRTCCloudDef.TRTC_VIDEO_ROTATION_0;
      }
      if (!renderParams.mirrorType) {
        renderParams.mirrorType = TRTCCloudDef.TRTC_VIDEO_MIRROR_TYPE_AUTO;
      }
      renderParams.streamType = streamType;
      renderParams.userId = userId;
    }
    if (
      Platform.OS === 'android' &&
      viewType === TRTCCloudDef.TRTC_VideoView_TextureView
    ) {
      return (
        <TXTextureView
          data={{ userId, streamType, frontCamera}}
          renderParams={renderParams}
          {...otherProps}
        />
      );
    } else {
      return (
        <TXSurfaceView
          data={{ userId, streamType, frontCamera}}
          renderParams={renderParams}
          {...otherProps}
        />
      );
    }
  }
}

/**
 * @ignore
 */
const TXTextureView = requireNativeComponent<
  TXRenderViewProps & TRTCRenderParams
>('TXVideoTextureView');
