export class PostParams {
	private static instance: PostParams;
	private postParams: Array<object>;
	private postDetailParams: Array<object>;

	private constructor() {
		this.postParams = [];
		this.postDetailParams = [];
	}

	public static getInstance(): PostParams {
		if (!PostParams.instance) {
			PostParams.instance = new PostParams();
		}
		return PostParams.instance;
	}

	public addItem(item: object): void {
		const isDuplicate = this.postParams.some((existingItem: any) => {
			if (item && existingItem) {
				const itemWhere = (item as any).where;
				const existingWhere = existingItem.where;
				return (
					itemWhere?.parentId === existingWhere?.parentId &&
					itemWhere?.type === existingWhere?.type
				);
			}
			return false;
		});

		if (!isDuplicate) {
			this.postParams.push(item);
		}
	}

	public addDetailItem(item: object): void {
		const isDuplicate = this.postDetailParams.some((existingItem: any) => {
			if (item && existingItem) {
				const itemWhere = (item as any).where;
				const existingWhere = existingItem.where;
				return itemWhere?.id === existingWhere?.id;
			}
			return false;
		});

		if (!isDuplicate) {
			this.postDetailParams.push(item);
		}
	}

	public removeItem(item: object): void {
		this.postParams = this.postParams.filter((existingItem: any) => {
			if (item && existingItem) {
				const itemWhere = (item as any).where;
				const existingWhere = existingItem.where;
				return !(
					itemWhere?.parentId === existingWhere?.parentId &&
					itemWhere?.type === existingWhere?.type
				);
			}
			return true;
		});
	}

	public removeDetailItem(item: object): void {
		this.postDetailParams = this.postDetailParams.filter(
			(existingItem: any) => {
				if (item && existingItem) {
					const itemWhere = (item as any).where;
					const existingWhere = existingItem.where;
					return !(itemWhere?.id === existingWhere?.id);
				}
				return true;
			}
		);
	}

	public getItems(): Array<object> {
		return [...this.postParams];
	}

	public getDetailItems(): Array<object> {
		return [...this.postDetailParams];
	}
}
