import * as SQLite from 'expo-sqlite';
import NetInfo, { NetInfoState } from '@react-native-community/netinfo';
import { StoreType, storage } from 'src/storage';
import { fetchLimitedRanking, fetchLpi, fetchInHistory, fetchInMemoriam } from '@api/ranking';
import { initTilesDownload } from './tilesService';
import { downloadFlags } from './flagsService';
import { fetchAndSaveAllTypesAndMasters } from './unMastersService';
import { updateAvatars } from './avatarsService';
import { fetchAndSaveStatistics } from './statisticsService';
import { saveTriumphsData } from './triumphsService';
import { saveSeriesRankingData } from './seriesRankingService';
import { updateDarePlacesDb, updateNmRegionsDb } from 'src/db';
import { refreshJsonData } from './geojsonService';

const db = SQLite.openDatabase('nomadManiaDb.db');
const lastUpdateDate = storage.get('lastUpdateDate', StoreType.STRING) as string || '1990-01-01';
const lastUpdateNmRegions = storage.get('lastUpdateNmRegions', StoreType.STRING) as string || '1990-01-01';
const lastUpdateDarePlaces = storage.get('lastUpdateDarePlaces', StoreType.STRING) as string || '1990-01-01';

export const initializeDatabase = (): Promise<void> => {
  return new Promise<void>((resolve, reject) => {
    db.transaction(tx => {
      createSyncTriggers('tableName');

      resolve();
    }, error => {
      console.error('DB initialization error: ', error);
      reject(error);
    });
  });
};

const createSyncTriggers = (tableName: string): void => {
};

export const checkInternetConnection = async (): Promise<NetInfoState> => {
  const state = await NetInfo.fetch();
  return state;
};

export const syncDataWithServer = async (): Promise<void> => {
  const userId = storage.get('uid', StoreType.STRING) as string;
  const { isConnected } = await checkInternetConnection();

  if (isConnected) {
    console.log('Syncing data with server...');
    processSyncQueue();
    await refreshJsonData();
    await updateMasterRanking();
    await downloadFlags();
    await updateAvatars(lastUpdateDate);
    await updateNmRegionsDb(lastUpdateNmRegions);
    await updateDarePlacesDb(lastUpdateDarePlaces);
    await initTilesDownload(userId);
  }
};

const processSyncQueue = (): void => {
};

export const updateStaticGeoJSON = async (): Promise<void> => {
};

export const setupDatabaseAndSync = async (): Promise<void> => {
  await initializeDatabase();
  await syncDataWithServer();
  await updateStaticGeoJSON();
};

const updateMasterRanking = async () => {
  const token = storage.get('token', StoreType.STRING) as string || '';
  const dataLimitedRanking = await fetchLimitedRanking();

  if (dataLimitedRanking && dataLimitedRanking.data) {
    storage.set('masterRanking', JSON.stringify(dataLimitedRanking.data));
  }

  const dataLpi = await fetchLpi();

  if (dataLpi && dataLpi.data) {
    storage.set('lpiRanking', JSON.stringify(dataLpi.data));
  }

  const dataInHistory = await fetchInHistory();

  if (dataInHistory && dataInHistory.data) {
    storage.set('inHistoryRanking', JSON.stringify(dataInHistory.data));
  }

  const dataInMemoriam = await fetchInMemoriam();

  if (dataInMemoriam && dataInMemoriam.data) {
    storage.set('inMemoriamRanking', JSON.stringify(dataInMemoriam.data));
  }

  await fetchAndSaveStatistics(token);
  await fetchAndSaveAllTypesAndMasters();
  await saveTriumphsData();
  await saveSeriesRankingData();
};

export default setupDatabaseAndSync;
