/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2020  SteamWar.de-Serverteam
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.sql;

import de.steamwar.sql.internal.Field;
import de.steamwar.sql.internal.SelectStatement;
import de.steamwar.sql.internal.Statement;
import de.steamwar.sql.internal.Table;
import lombok.AllArgsConstructor;

import java.util.UUID;

@AllArgsConstructor
public class UserConfig {

    private static final Table<UserConfig> table = new Table<>(UserConfig.class);
    private static final SelectStatement<UserConfig> select = table.select(Table.PRIMARY);
    private static final Statement insert = table.insertAll();
    private static final Statement delete = table.delete(Table.PRIMARY);

    @Field(keys = {Table.PRIMARY})
    private final int user;
    @Field(keys = {Table.PRIMARY})
    private final String config;
    @Field
    private final String value;

    public static String getConfig(UUID player, String config) {
        return getConfig(SteamwarUser.get(player).getId(), config);
    }

    public static String getConfig(int player, String config) {
        UserConfig value = select.select(player, config);
        return value != null ? value.value : null;
    }

    public static void updatePlayerConfig(UUID uuid, String config, String value) {
        updatePlayerConfig(SteamwarUser.get(uuid).getId(), config, value);
    }

    public static void updatePlayerConfig(int id, String config, String value) {
        if (value == null) {
            removePlayerConfig(id, config);
            return;
        }
        insert.update(id, config, value);
    }

    public static void removePlayerConfig(UUID uuid, String config) {
        removePlayerConfig(SteamwarUser.get(uuid).getId(), config);
    }

    public static void removePlayerConfig(int id, String config) {
        delete.update(id, config);
    }
}
