import UUID from "../Utils/UUID";
import DatabaseProperty from "./Database/DatabaseProperty";
import BadDataException from "./Exception/BadDataException";
import BadOperationException from "./Exception/BadOperationException";
import { ObjectType } from "./JSON";
import CryptoJS from "crypto-js";
export default class HashedString extends DatabaseProperty {
    get value() {
        return this._value;
    }
    set value(v) {
        this._value = v;
    }
    constructor(value, isValueHashed = false) {
        super();
        this.isHashed = false;
        this._value = "";
        this.value = value;
        this.isHashed = isValueHashed;
    }
    toJSON() {
        return {
            _type: ObjectType.HashedString,
            value: this.toString(),
        };
    }
    static fromJSON(json) {
        if (json["_type"] === ObjectType.HashedString) {
            return new HashedString(json["value"] || "");
        }
        throw new BadDataException("Invalid JSON: " + JSON.stringify(json));
    }
    toString() {
        return this.value;
    }
    static generate() {
        return new this(UUID.generate());
    }
    static toDatabase(value) {
        if (value) {
            if (typeof value === "string") {
                value = new HashedString(value);
            }
            return value.toString();
        }
        return null;
    }
    isValueHashed() {
        return this.isHashed;
    }
    async hashValue(encryptionSecret) {
        if (!this.value) {
            return "";
        }
        if (this.isHashed) {
            throw new BadOperationException("Value is already hashed");
        }
        const valueToHash = (encryptionSecret || "") + this.value;
        this.isHashed = true;
        this.value = CryptoJS.SHA256(valueToHash).toString();
        return this.value;
    }
    static async hashValue(value, encryptionSecret) {
        const hashstring = new HashedString(value, false);
        return await hashstring.hashValue(encryptionSecret);
    }
    static fromDatabase(_value) {
        if (_value) {
            return new HashedString(_value, true);
        }
        return null;
    }
    static fromString(value) {
        return new HashedString(value, false);
    }
}
//# sourceMappingURL=HashedString.js.map