import * as vscode from 'vscode';
import { GitChangeType, Schemes } from '../../common';
import { TreeNode } from './treeNode';

export class FileChangeNode extends TreeNode implements vscode.TreeItem {
	public description: string;
	public iconPath: vscode.ThemeIcon;
	public fileChangeResourceUri: vscode.Uri;
	public command: vscode.Command;

	constructor(
		// public readonly path: string,
		public readonly fileName: string,
		public readonly previousFileName: string | undefined,
		public readonly status: GitChangeType,
		public readonly baseCommit: string,
		public readonly headCommit: string,
		public readonly mergeId: number,
	) {
		super();
		const paths = fileName.split('/');
		const _fileName = paths.pop();
		this.label = _fileName;
		this.description = paths.join('/');
		this.iconPath = vscode.ThemeIcon.File;
		this.fileChangeResourceUri = vscode.Uri.file(fileName).with({
			scheme: Schemes.CodingMr,
			query: JSON.stringify({ status, fileName }),
		});

		const queryParams = { fileName, baseCommit, headCommit, status, mergeId };

		let parentURI = vscode.Uri.file(fileName).with({
			scheme: Schemes.CodingMr,
			query: JSON.stringify({ ...queryParams, commit: baseCommit, isBase: false }),
		});

		let headURI = vscode.Uri.file(fileName).with({
			scheme: Schemes.CodingMr,
			query: JSON.stringify({ ...queryParams, commit: headCommit, isBase: true }),
		});

		switch (status) {
			case GitChangeType.ADD:
				parentURI = vscode.Uri.file(fileName).with({
					scheme: Schemes.CodingMr,
					query: JSON.stringify({ ...queryParams, commit: baseCommit, isBase: false, isEmpty: true }),
				});
				break;

			case GitChangeType.RENAME:
				// FIXME: RENAME 类型 previousFileName 有问题
				parentURI = vscode.Uri.file(previousFileName!).with({
					scheme: Schemes.CodingMr,
					query: JSON.stringify({ ...queryParams, commit: baseCommit, isBase: false, isEmpty: true }),
				});
				break;

			case GitChangeType.DELETE:
				headURI = vscode.Uri.file(fileName).with({
					scheme: Schemes.CodingMr,
					query: JSON.stringify({
						...queryParams,
						fileName,
						commit: headCommit,
						isBase: true,
						isEmpty: true,
					}),
				});
				break;
		}

		this.command = {
			title: 'Open Diff',
			command: 'coding.showDiff',
			arguments: [parentURI, headURI, `${fileName} (Merge Request Preview)`],
		};
	}

	get resourceUri(): vscode.Uri {
		return vscode.Uri.file(this.fileName).with({ query: this.fileChangeResourceUri.query });
	}

	getTreeItem() {
		return this;
	}
}
