import RNFS from 'react-native-fs';
import { unzip } from 'react-native-zip-archive';

export const downloadToFile = async (
  fileUrl: string,
  fileName: string,
  listener?: (
    bytesWritten: number,
    contentLength: number,
    progress: string,
  ) => void,
) => {
  // /storage/emulated/0/Android/data/com.trust.ywx/files/bundles/android/common.android.bundle
  const downloadDest = `${RNFS.ExternalDirectoryPath}/bundles/${fileName}`;

  const fileExists = await RNFS.exists(downloadDest);
  if (fileExists) {
    await RNFS.unlink(downloadDest);
  }

  const options = {
    fromUrl: fileUrl,
    toFile: downloadDest,
    progress: (res: any) => {
      listener &&
        listener(
          res.bytesWritten,
          res.contentLength,
          `进度: ${((res.bytesWritten / res.contentLength) * 100).toFixed(2)}%`,
        );
      console.log(
        `进度: ${((res.bytesWritten / res.contentLength) * 100).toFixed(2)}%`,
      );
    },
  };

  try {
    const res = await RNFS.downloadFile(options).promise;
    console.log('文件已下载到沙盒:', downloadDest, res);
    const exists = await RNFS.exists(downloadDest);
    if (exists) {
      const result = await unzip(
        downloadDest,
        `${RNFS.ExternalDirectoryPath}/bundles/`,
      );
      console.log('文件已解压到沙盒:', downloadDest, result);
    }
    return downloadDest;
  } catch (error) {
    console.error('下载失败:', error);
  }
};
