import { FileSystem } from 'src/utils';
import { API_HOST } from 'src/constants';

const downloadFlag = async (flagId: number) => {
  try {
    const flagUrl = `${API_HOST}/img/flags_new/${flagId}.png`;
    const fileName = `${flagId}.png`;
    let fileUri = `${FileSystem.documentDirectory}flags/${fileName}`;

    await FileSystem.downloadAsync(flagUrl, fileUri);
  } catch (error) {
    console.error('Error downloading flags: ', error);
  }
};

export const downloadFlags = async () => {
  const totalFlags = 635;
  const dirInfo = await FileSystem.getInfoAsync(`${FileSystem.documentDirectory}flags`);

  if (!dirInfo.exists) {
    await FileSystem.makeDirectoryAsync(`${FileSystem.documentDirectory}flags`, { intermediates: true });

    for (let flagId = 1; flagId <= totalFlags; flagId++) {
      try {
        await downloadFlag(flagId);
      } catch (error) {
        console.error(`Error downloading flag ${flagId}:`, error);
      }
    }
  }
}
