import { SQLiteDatabase } from 'expo-sqlite/legacy';

export const getData = async (
  db: SQLiteDatabase | null, 
  regionId: number, 
  name: string, 
  callback: (data: any, avatars: string[]) => void
) => {
  return new Promise<void>((resolve, reject) => {
    db?.transaction(tx => {
      tx.executeSql(
        `SELECT * FROM ${name} WHERE id = ${regionId};`,
        [],
        (_, { rows }) => {
          const regionData = rows._array[0];
  
          const avatarPromises = regionData?.visitors_avatars
            ? JSON.parse(regionData.visitors_avatars)?.map((avatarId: number) => {
              return new Promise<string>((resolveAvatar, rejectAvatar) => {
                tx.executeSql(
                  `SELECT * FROM avatars WHERE id = ${avatarId};`,
                  [],
                  (_, { rows }) => resolveAvatar(rows._array[0].data),
                  (_, error) => {
                    console.error('error', error);
                    rejectAvatar(error);
                    return false;
                  }
                );
              });
            })
            : [];
  
          Promise.all(avatarPromises)
            .then(avatars => {
              callback(regionData, avatars);
              resolve();
            })
            .catch(error => {
              console.error('Error processing avatars', error);
              reject(error);
            });
        },
        (_, error) => {
          console.error('error', error);
          reject(error);
          return false;
        }
      );
    });
  });
};
