import { preferences } from '@kit.ArkData';

const CONFIG_STORE = 'app_config';
const KEY_SERVER_URL = 'server_url';
const DEFAULT_SERVER = 'http://192.168.1.1:9255';

let configStore: preferences.Preferences | null = null;

async function getStore(): Promise<preferences.Preferences> {
  if (configStore === null) {
    configStore = await preferences.getPreferences(getContext(), CONFIG_STORE);
  }
  return configStore;
}

export async function getServerUrl(): Promise<string> {
  try {
    const store = await getStore();
    const url = await store.get(KEY_SERVER_URL, DEFAULT_SERVER);
    return (url as string) || DEFAULT_SERVER;
  } catch (_e) {
    return DEFAULT_SERVER;
  }
}

export async function setServerUrl(url: string): Promise<void> {
  try {
    const store = await getStore();
    await store.put(KEY_SERVER_URL, url);
    await store.flush();
  } catch (e) {
    console.error('setServerUrl failed: ' + e);
  }
}
