export class Permissions {
	static readonly AdminRead = 2;
	static readonly AdminWrite = 4;
	static readonly UserRead = 8;
	static readonly UserWrite = 16;
	static readonly ReportRead = 32;
	static readonly ReportWrite = 64;
	static readonly SettingsRead = 128;
	static readonly SettingsWrite = 256;

	readonly value: number;

	constructor(value: number | number[] | null) {
		if (typeof value == 'number') {
			this.value = value;
		} else if (value == null) {
			this.value = 0;
		} else {
			let finalValue = 0;
			for (const v of Object.values(value)) {
				finalValue |= v;
			}
			this.value = finalValue;
		}
	}

	toJSON() {
		return this.value;
	}

	static allPermissions(): number[] {
		return [
			Permissions.AdminRead,
			Permissions.AdminWrite,
			Permissions.UserRead,
			Permissions.UserWrite,
			Permissions.ReportRead,
			Permissions.ReportWrite,
			Permissions.SettingsRead,
			Permissions.SettingsWrite
		];
	}

	adminRead(): boolean {
		return (this.value & Permissions.AdminRead) != 0;
	}
	adminWrite(): boolean {
		return (this.value & Permissions.AdminWrite) != 0;
	}
	userRead(): boolean {
		return (this.value & Permissions.UserRead) != 0;
	}
	userWrite(): boolean {
		return (this.value & Permissions.UserWrite) != 0;
	}
	reportRead(): boolean {
		return (this.value & Permissions.ReportRead) != 0;
	}
	reportWrite(): boolean {
		return (this.value & Permissions.ReportWrite) != 0;
	}
	settingsRead(): boolean {
		return (this.value & Permissions.SettingsRead) != 0;
	}
	settingsWrite(): boolean {
		return (this.value & Permissions.SettingsWrite) != 0;
	}

	asArray(): number[] {
		const array = [];
		for (const perm of Permissions.allPermissions()) {
			if ((this.value & perm) != 0) {
				array.push(perm);
			}
		}
		return array;
	}
}
