import { ThemeIcon, TreeItem, TreeItemCollapsibleState } from 'vscode';
import { map } from '@gitlens/utils/iterable.js';
import type { GitUri } from '../../git/gitUri.js';
import type { GlRepository } from '../../git/models/repository.js';
import type { ViewsWithStashesNode } from '../viewBase.js';
import { CacheableChildrenViewNode } from './abstract/cacheableChildrenViewNode.js';
import type { ViewNode } from './abstract/viewNode.js';
import { ContextValues, getViewNodeId } from './abstract/viewNode.js';
import { MessageNode } from './common.js';
import { StashNode } from './stashNode.js';

export class StashesNode extends CacheableChildrenViewNode<'stashes', ViewsWithStashesNode> {
	constructor(
		uri: GitUri,
		view: ViewsWithStashesNode,
		protected override parent: ViewNode,
		public readonly repo: GlRepository,
	) {
		super('stashes', uri, view, parent);

		this.updateContext({ repository: repo });
		this._uniqueId = getViewNodeId(this.type, this.context);
	}

	override get id(): string {
		return this._uniqueId;
	}

	get repoPath(): string {
		return this.repo.path;
	}

	async getChildren(): Promise<ViewNode[]> {
		if (this.children == null) {
			const stash = await this.repo.git.stash?.getStash();
			if (!stash?.stashes.size) return [new MessageNode(this.view, this, 'No stashes could be found.')];

			this.children = [...map(stash.stashes.values(), c => new StashNode(this.view, this, c))];
		}

		return this.children;
	}

	getTreeItem(): TreeItem {
		const item = new TreeItem('Stashes', TreeItemCollapsibleState.Collapsed);
		item.id = this.id;
		item.contextValue = ContextValues.Stashes;
		item.iconPath = new ThemeIcon('gitlens-stashes');
		return item;
	}
}
