import * as FileSystem from 'expo-file-system';
import { Asset } from 'expo-asset';
import { API_HOST } from 'src/constants';
import axios from 'axios';

const jsonFileName = 'mqp.json';
const jsonFileUri = `${FileSystem.documentDirectory}${jsonFileName}`;

let jsonData: any = null;

const fetchLocalJsonData = async () => {
  try {
    const fileInfo = await FileSystem.getInfoAsync(jsonFileUri);
    if (fileInfo.exists) {
      const json = await FileSystem.readAsStringAsync(jsonFileUri);
      return JSON.parse(json);
    } else {
      const asset = Asset.fromModule(require('../../../assets/geojson/mqp.json'));
      await asset.downloadAsync();
      const json = await FileSystem.readAsStringAsync(asset?.localUri as string);
      return JSON.parse(json);
    }
  } catch (error) {
    console.error('Failed to load local JSON data:', error);
    return null;
  }
};

const saveJsonDataToLocal = async (data: any) => {
  try {
    await FileSystem.writeAsStringAsync(jsonFileUri, JSON.stringify(data));
  } catch (error) {
    console.error('Failed to save JSON data to local storage:', error);
  }
};

export const fetchJsonData = async () => {
  if (jsonData) {
    return jsonData;
  }

  try {
    const response = await axios.get(`${API_HOST}/static/json/mqp.geojson`);
    if (response.status !== 200) {
      throw new Error('Network response error');
    }
    jsonData = response.data;
    await saveJsonDataToLocal(jsonData);
  } catch (error) {
    console.error('Failed to fetch JSON data from server:', error);
    jsonData = await fetchLocalJsonData();
  }

  return jsonData;
};

export const refreshJsonData = async () => {
  jsonData = null;
  return await fetchJsonData();
};

(async () => {
  jsonData = await fetchJsonData();
})();

export default jsonData;
