"use strict";

import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { StyleSheet, findNodeHandle } from 'react-native';
import NativeTuiplayer from "./NativeTuiplayer.js";
import TuiplayerShortVideoNativeComponent, { Commands } from './TuiplayerShortVideoViewNativeComponent';
import { jsx as _jsx } from "react/jsx-runtime";
export const initialize = config => {
  NativeTuiplayer.initialize(config);
};
const nativeConstants = NativeTuiplayer.getShortVideoConstants ? NativeTuiplayer.getShortVideoConstants() : undefined;
const FALLBACK_PLAY_MODE = Object.freeze({
  MODE_LIST_LOOP: 0,
  MODE_ONE_LOOP: 1,
  MODE_CUSTOM: 2
});
const FALLBACK_RESOLUTION_TYPE = Object.freeze({
  GLOBAL: 0,
  CURRENT: 1
});
/**
 * TUIVideoConst.ListPlayMode 对应的播放模式常量。
 */
export const TuiplayerListPlayMode = Object.freeze({
  ...FALLBACK_PLAY_MODE,
  ...nativeConstants?.listPlayMode
});

/**
 * TUIConstants.TUIResolutionType 对应的分辨率切换目标常量。
 */
export const TuiplayerResolutionType = Object.freeze({
  ...FALLBACK_RESOLUTION_TYPE,
  ...nativeConstants?.resolutionType
});
export const TuiplayerShortVideoView = /*#__PURE__*/forwardRef(({
  sources,
  autoPlay = true,
  style,
  initialIndex = -1,
  paused = false,
  playMode,
  userInputEnabled = true,
  pageScrollMsPerInch,
  layers,
  vodStrategy,
  liveStrategy,
  onPageChanged,
  onEndReached,
  onVodEvent,
  onReady: onReadyProp
}, ref) => {
  const nativeRef = useRef(null);
  const [nativeReady, setNativeReady] = useState(false);
  const nativeReadyRef = useRef(false);
  const pendingNativeCommands = useRef([]);
  const flushPendingNativeCommands = useCallback(() => {
    if (!nativeReadyRef.current) {
      return;
    }
    const view = nativeRef.current;
    if (!view) {
      return;
    }
    const queue = pendingNativeCommands.current;
    pendingNativeCommands.current = [];
    queue.forEach(command => {
      try {
        command(view);
      } catch (error) {
        console.warn('[ShortVideo] 执行原生命令失败:', error);
      }
    });
  }, []);
  const runOrQueueNativeCommand = useCallback(command => {
    const view = nativeRef.current;
    if (nativeReadyRef.current && view) {
      try {
        command(view);
      } catch (error) {
        console.warn('[ShortVideo] 执行原生命令失败:', error);
      }
    } else {
      pendingNativeCommands.current.push(command);
    }
  }, []);
  useEffect(() => {
    return () => {
      nativeReadyRef.current = false;
      pendingNativeCommands.current = [];
    };
  }, []);
  useEffect(() => {
    if (nativeReady) {
      flushPendingNativeCommands();
    }
  }, [nativeReady, flushPendingNativeCommands]);
  const buildSourcePayload = useCallback(item => ({
    type: item.type ?? 'fileId',
    appId: item.appId,
    fileId: item.fileId,
    url: item.url,
    coverPictureUrl: item.coverPictureUrl,
    pSign: item.pSign,
    extViewType: item.extViewType,
    autoPlay: item.autoPlay,
    videoConfig: item.videoConfig,
    meta: item.meta
  }), []);
  const toNativeSource = useCallback(item => buildSourcePayload(item), [buildSourcePayload]);
  const normalizedSources = useMemo(() => {
    return sources.map(toNativeSource);
  }, [sources, toNativeSource]);
  const effectiveSources = useMemo(() => {
    if (nativeReady) {
      return normalizedSources;
    }
    return [];
  }, [nativeReady, normalizedSources]);
  const handleNativeReady = useCallback(() => {
    if (nativeReadyRef.current) {
      return;
    }
    nativeReadyRef.current = true;
    setNativeReady(true);
    if (typeof onReadyProp === 'function') {
      onReadyProp();
    }
  }, [onReadyProp]);
  const normalizedVodStrategy = useMemo(() => {
    if (!vodStrategy) {
      return undefined;
    }
    return {
      preloadCount: vodStrategy.preloadCount,
      preDownloadSize: vodStrategy.preDownloadSize,
      preLoadBufferSize: vodStrategy.preLoadBufferSize,
      maxBufferSize: vodStrategy.maxBufferSize,
      preferredResolution: vodStrategy.preferredResolution ? normalizePreferredResolution(vodStrategy.preferredResolution) : undefined,
      progressInterval: vodStrategy.progressInterval,
      renderMode: vodStrategy.renderMode,
      mediaType: vodStrategy.mediaType,
      resumeMode: typeof vodStrategy.resumeMode === 'number' ? String(vodStrategy.resumeMode) : vodStrategy.resumeMode,
      enableAutoBitrate: vodStrategy.enableAutoBitrate,
      enableAccurateSeek: vodStrategy.enableAccurateSeek,
      audioNormalization: vodStrategy.audioNormalization,
      retainPreVod: vodStrategy.retainPreVod,
      superResolutionMode: typeof vodStrategy.superResolutionMode === 'number' ? String(vodStrategy.superResolutionMode) : vodStrategy.superResolutionMode,
      retryCount: vodStrategy.retryCount,
      prePlayStrategy: vodStrategy.prePlayStrategy
    };
  }, [vodStrategy]);
  const normalizedLiveStrategy = useMemo(() => {
    if (!liveStrategy) {
      return undefined;
    }
    return {
      renderMode: liveStrategy.renderMode,
      retainPreLive: liveStrategy.retainPreLive,
      prePlayStrategy: liveStrategy.prePlayStrategy
    };
  }, [liveStrategy]);
  const serializeVodOptions = useCallback((_command, options) => {
    if (options == null) {
      return undefined;
    }
    const payload = {};
    for (const [key, value] of Object.entries(options)) {
      if (value == null) {
        continue;
      }
      if (key === 'source' && typeof value === 'object') {
        payload.source = buildSourcePayload(value);
      } else if (key === 'sources' && Array.isArray(value)) {
        payload.sources = value.map(item => buildSourcePayload(item));
      } else {
        payload[key] = value;
      }
    }
    return payload;
  }, [buildSourcePayload]);
  const invokeVodPlayer = useCallback(async (command, options) => {
    if (!nativeReadyRef.current || nativeRef.current == null) {
      throw new Error('TuiplayerShortVideoView native instance is not ready.');
    }
    const viewTag = findNodeHandle(nativeRef.current);
    if (viewTag == null) {
      throw new Error('Unable to resolve native view tag');
    }
    const payload = serializeVodOptions(command, options);
    const result = await NativeTuiplayer.callShortVideoVodPlayer(viewTag, command, payload);
    return result;
  }, [nativeRef, serializeVodOptions]);
  const vodPlayerHandle = useMemo(() => ({
    startPlay: async (source, options) => {
      await invokeVodPlayer('startPlay', {
        ...options,
        source
      });
    },
    resume: async options => {
      await invokeVodPlayer('resumePlay', options);
    },
    pause: async options => {
      await invokeVodPlayer('pause', options);
    },
    stop: async options => {
      await invokeVodPlayer('stop', options);
    },
    seekTo: async (time, options) => {
      await invokeVodPlayer('seekTo', {
        ...options,
        time
      });
    },
    isPlaying: options => invokeVodPlayer('isPlaying', options),
    setLoop: async (loop, options) => {
      await invokeVodPlayer('setLoop', {
        ...options,
        loop
      });
    },
    isLoop: options => invokeVodPlayer('isLoop', options),
    setRate: async (rate, options) => {
      await invokeVodPlayer('setRate', {
        ...options,
        rate
      });
    },
    getDuration: options => invokeVodPlayer('getDuration', options),
    getCurrentPlaybackTime: options => invokeVodPlayer('getCurrentPlaybackTime', options),
    getPlayableDuration: options => invokeVodPlayer('getPlayableDuration', options),
    setMute: async (mute, options) => {
      await invokeVodPlayer('setMute', {
        ...options,
        mute
      });
    },
    setAudioPlayoutVolume: async (volume, options) => {
      await invokeVodPlayer('setAudioPlayoutVolume', {
        ...options,
        volume
      });
    },
    setMirror: async (mirror, options) => {
      await invokeVodPlayer('setMirror', {
        ...options,
        mirror
      });
    },
    setBitrateIndex: async (index, options) => {
      await invokeVodPlayer('setBitrateIndex', {
        ...options,
        index
      });
    },
    getBitrateIndex: options => invokeVodPlayer('getBitrateIndex', options),
    getSupportResolution: options => invokeVodPlayer('getSupportResolution', options),
    setRenderRotation: async (rotation, options) => {
      await invokeVodPlayer('setRenderRotation', {
        ...options,
        rotation
      });
    },
    setRenderMode: async (mode, options) => {
      await invokeVodPlayer('setRenderMode', {
        ...options,
        mode
      });
    },
    getWidth: options => invokeVodPlayer('getWidth', options),
    getHeight: options => invokeVodPlayer('getHeight', options),
    switchResolution: (resolution, options) => invokeVodPlayer('switchResolution', {
      ...options,
      resolution
    }),
    setAudioNormalization: async (value, options) => {
      await invokeVodPlayer('setAudioNormalization', {
        ...options,
        value
      });
    },
    enableHardwareDecode: (enable, options) => invokeVodPlayer('enableHardwareDecode', {
      ...options,
      enable
    })
  }), [invokeVodPlayer]);
  useImperativeHandle(ref, () => ({
    startPlayIndex: (index, smooth = false) => {
      runOrQueueNativeCommand(view => {
        Commands.startPlayIndex(view, index, smooth);
      });
    },
    setPlayMode: mode => {
      runOrQueueNativeCommand(view => {
        Commands.setPlayMode(view, mode);
      });
    },
    release: () => {
      runOrQueueNativeCommand(view => {
        Commands.release(view);
      });
    },
    resume: () => {
      runOrQueueNativeCommand(view => {
        Commands.resume(view);
      });
    },
    switchResolution: (resolution, target) => {
      runOrQueueNativeCommand(view => {
        Commands.switchResolution(view, resolution, target);
      });
    },
    pausePreload: () => {
      runOrQueueNativeCommand(view => {
        Commands.pausePreload(view);
      });
    },
    resumePreload: () => {
      runOrQueueNativeCommand(view => {
        Commands.resumePreload(view);
      });
    },
    setUserInputEnabled: enabled => {
      runOrQueueNativeCommand(view => {
        Commands.setUserInputEnabled(view, enabled);
      });
    },
    syncPlaybackState: () => {
      runOrQueueNativeCommand(view => {
        Commands.syncPlaybackState(view);
      });
    },
    updateMeta: (index, meta) => {
      runOrQueueNativeCommand(view => {
        Commands.updateMeta(view, index, normalizeOverlayMeta(meta));
      });
    },
    getCurrentSource: async () => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return null;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return null;
      }
      return NativeTuiplayer.getCurrentShortVideoSource(viewTag);
    },
    getDataCount: async () => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return 0;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return 0;
      }
      return NativeTuiplayer.getShortVideoDataCount(viewTag);
    },
    getDataByIndex: async index => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return null;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return null;
      }
      return NativeTuiplayer.getShortVideoDataByIndex(viewTag, index);
    },
    removeData: async index => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      await NativeTuiplayer.removeShortVideoData(viewTag, index);
    },
    removeRangeData: async (index, count) => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      await NativeTuiplayer.removeShortVideoRange(viewTag, index, count);
    },
    removeDataByIndexes: async indexes => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      await NativeTuiplayer.removeShortVideoDataByIndexes(viewTag, indexes);
    },
    addData: async (source, index = -1) => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      const payload = buildSourcePayload(source);
      await NativeTuiplayer.addShortVideoData(viewTag, payload, index);
    },
    addRangeData: async (list, startIndex = -1) => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      const payload = list.map(buildSourcePayload);
      await NativeTuiplayer.addShortVideoRange(viewTag, payload, startIndex);
    },
    replaceData: async (source, index = -1) => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      const payload = buildSourcePayload(source);
      await NativeTuiplayer.replaceShortVideoData(viewTag, payload, index);
    },
    replaceRangeData: async (list, startIndex) => {
      if (!nativeReadyRef.current || nativeRef.current == null) {
        return;
      }
      const viewTag = findNodeHandle(nativeRef.current);
      if (viewTag == null) {
        return;
      }
      const payload = list.map(buildSourcePayload);
      await NativeTuiplayer.replaceShortVideoRange(viewTag, payload, startIndex);
    },
    vodPlayer: vodPlayerHandle
  }), [buildSourcePayload, runOrQueueNativeCommand, vodPlayerHandle]);
  const normalizedLayers = useMemo(() => {
    if (!layers) {
      return undefined;
    }
    return {
      vodLayers: layers.vodLayers,
      liveLayers: layers.liveLayers,
      customLayers: layers.customLayers
    };
  }, [layers]);
  return /*#__PURE__*/_jsx(TuiplayerShortVideoNativeComponent, {
    ref: nativeRef,
    style: StyleSheet.compose(styles.container, style),
    sources: effectiveSources,
    autoPlay: autoPlay,
    initialIndex: initialIndex,
    paused: paused,
    playMode: playMode ?? -1,
    userInputEnabled: userInputEnabled,
    pageScrollMsPerInch: pageScrollMsPerInch,
    layers: normalizedLayers,
    vodStrategy: normalizedVodStrategy,
    liveStrategy: normalizedLiveStrategy,
    onPageChanged: onPageChanged,
    onEndReached: onEndReached,
    onVodEvent: onVodEvent,
    onReady: handleNativeReady
  });
});
const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});
function normalizePreferredResolution(value) {
  if (!value) {
    return undefined;
  }
  return {
    width: value.width,
    height: value.height
  };
}
function normalizeOverlayMeta(meta) {
  return {
    authorName: meta.authorName,
    authorAvatar: meta.authorAvatar,
    title: meta.title,
    likeCount: typeof meta.likeCount === 'number' && Number.isFinite(meta.likeCount) ? meta.likeCount : undefined,
    commentCount: typeof meta.commentCount === 'number' && Number.isFinite(meta.commentCount) ? meta.commentCount : undefined,
    favoriteCount: typeof meta.favoriteCount === 'number' && Number.isFinite(meta.favoriteCount) ? meta.favoriteCount : undefined,
    isLiked: meta.isLiked,
    isBookmarked: meta.isBookmarked,
    isFollowed: meta.isFollowed,
    watchMoreText: meta.watchMoreText
  };
}
//# sourceMappingURL=index.js.map