/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2023  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 lombok.Getter;

import java.util.List;

@AllArgsConstructor
@Getter
public class Script {

    private static final Table<Script> table = new Table<>(Script.class);

    private static final SelectStatement<Script> byId = table.select(Table.PRIMARY);
    private static final SelectStatement<Script> byUserName = table.select("nameUser");
    private static final SelectStatement<Script> byUser = table.selectFields("userId");

    private static final Statement insert = table.insertFields(true, "userId", "name", "code");
    private static final Statement updateName = table.update(Table.PRIMARY, "name");
    private static final Statement updateCode = table.update(Table.PRIMARY, "code");
    private static final Statement delete = table.delete(Table.PRIMARY);

    public static Script get(int id) {
        return byId.select(id);
    }

    public static Script get(SteamwarUser user, String name) {
        return byUserName.select(user, name);
    }

    public static Script create(SteamwarUser user, String name, String code) {
        return new Script(insert.insertGetKey(user, name, code), user.getId(), name, code);
    }

    public static List<Script> list(SteamwarUser user) {
        return byUser.listSelect(user);
    }

    @Field(keys = Table.PRIMARY, autoincrement = true)
    private final int id;
    @Field(keys = "nameUser")
    private final int userId;
    @Field(keys = "nameUser")
    private String name;
    @Field
    private String code;

    public void setName(String name) {
        this.name = name;
        updateName.update(name, id);
    }

    public void setCode(String code) {
        this.code = code;
        updateCode.update(code, id);
    }

    public void delete() {
        delete.update(id);
    }
}
