001package net.tnemc.item.persistent;
002/*
003 * The New Item Library
004 * Copyright (C) 2022 - 2025 Daniel "creatorfromhell" Vidmar
005 *
006 * This program is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020
021import net.tnemc.item.JSONHelper;
022import org.json.simple.JSONObject;
023
024/**
025 * PersistentDataType
026 *
027 * @author creatorfromhell
028 * @since 0.2.0.0
029 */
030public abstract class PersistentDataType<T> {
031
032  protected String namespace;
033  protected String key;
034
035  protected T value;
036
037  public PersistentDataType(final String namespace, final String key) {
038
039    this.namespace = namespace;
040    this.key = key;
041  }
042
043  public String identifier() {
044
045    return namespace + ":" + key;
046  }
047
048  /**
049   * Returns the type of the PersistentDataType.
050   *
051   * @return The type of the PersistentDataType as a String.
052   * @since 0.2.0.0
053   */
054  public abstract String type();
055
056  /**
057   * Encodes the value of the PersistentDataType into a string representation.
058   *
059   * @return The encoded string representation of the value
060   * @since 0.2.0.0
061   */
062  public abstract String encode();
063
064  /**
065   * Decodes the given encoded string and sets the decoded value.
066   *
067   * @param encoded The string to be decoded
068   *
069   * @return The decoded value of type T
070   * @since 0.2.0.0
071   *
072   * @throws IllegalArgumentException if the encoded string is invalid
073   */
074  public abstract T decode(final String encoded) throws IllegalArgumentException;
075
076  /**
077   * Decodes the {@link JSONHelper JSON object} and sets the values in the current instance.
078   *
079   * @param json The {@link JSONHelper JSON object} to be decoded
080   * @since 0.2.0.0
081   */
082  public void readJSON(final JSONHelper json) {
083
084    this.value = decode(json.getString("value"));
085  }
086
087  public JSONObject toJSON() {
088
089    final JSONObject json = new JSONObject();
090    json.put("namespace", this.namespace);
091    json.put("key", this.key);
092    json.put("type", type());
093    json.put("value", encode());
094    return json;
095  }
096}