import { ThemeIcon, TreeItem, TreeItemCollapsibleState } from 'vscode';
import type { GitUri } from '../../git/gitUri.js';
import type { GlRepository } from '../../git/models/repository.js';
import type { ViewsWithRemotesNode } 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 { RemoteNode } from './remoteNode.js';

export class RemotesNode extends CacheableChildrenViewNode<'remotes', ViewsWithRemotesNode> {
	constructor(
		uri: GitUri,
		view: ViewsWithRemotesNode,
		protected override readonly parent: ViewNode,
		public readonly repo: GlRepository,
	) {
		super('remotes', 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 remotes = await this.repo.git.remotes.getRemotes({ sort: true });
			if (!remotes.length) {
				return [new MessageNode(this.view, this, 'No remotes could be found')];
			}

			const expand = remotes.length === 1;
			this.children = remotes.map(
				r => new RemoteNode(this.uri, this.view, this, this.repo, r, { expand: expand }),
			);
		}

		return this.children;
	}

	getTreeItem(): TreeItem {
		const item = new TreeItem('Remotes', TreeItemCollapsibleState.Collapsed);
		item.id = this.id;
		item.contextValue = ContextValues.Remotes;
		item.iconPath = new ThemeIcon('cloud');

		return item;
	}
}
