/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {STORAGE_KEY_SETTING_VALUES} from '../../../src/app/modules/settings/settings.provider';
import {Storage} from '@ionic/storage-angular';
import deepmerge from 'deepmerge';
import {STORAGE_KEY_CONFIG} from '../../../src/app/modules/config/config.provider';
import {SCIndexResponse} from '@openstapps/core';

export function storage(): Cypress.Chainable<Storage> {
  const storage = new Storage({});
  return cy.wrap(storage.create());
}

/**
 * Writes settings
 */
export function setSettings(settings: Record<string, Record<string, string>>) {
  return cy.storage().then(async storage => {
    const currentSettings = (await storage.get(STORAGE_KEY_SETTING_VALUES)) || {};
    console.log(deepmerge(currentSettings, settings));
    await storage.set(STORAGE_KEY_SETTING_VALUES, deepmerge(currentSettings, settings));
  });
}

export function getAllSettings(): Cypress.Chainable<Record<string, Record<string, string>> | undefined> {
  return cy.storage().invoke('get', STORAGE_KEY_SETTING_VALUES);
}

/**
 * Reads settings
 */
export function getSetting(group: string, key: string): Cypress.Chainable<string | undefined> {
  return cy.storage().then(async storage => {
    const currentSettings = await storage.get(STORAGE_KEY_SETTING_VALUES);
    return currentSettings?.[group]?.[key];
  });
}

/**
 *
 */
export function clearAllSettings() {
  return cy.storage().invoke('clear');
}

/**
 *
 */
export function setLocalConfig(config: SCIndexResponse | any) {
  cy.storage().invoke('set', STORAGE_KEY_CONFIG, config);
}
