import { _getFileCommitDetail } from '../codingApi';
import { CODING_FILE_SCHEME } from '../common';
import { ReadonlyFileSystemProvider } from './ReadonlyFileSystemProvider';

type GitHubRepository = any;

export async function getCodingFileContent(fileName: string, commit: string): Promise<Uint8Array> {
	let fileContent = '';

	try {
		const res = await _getFileCommitDetail({ file: fileName, commit });
		fileContent = res.data.file.data;
	} catch (error) {}

	return new TextEncoder().encode(fileContent);
}

export class CodingContentProvider extends ReadonlyFileSystemProvider {
	static scheme = CODING_FILE_SCHEME;

	constructor(public gitHubRepository: GitHubRepository) {
		super();
	}

	async readFile(uri: any): Promise<Uint8Array> {
		let params: Record<string, string> | undefined;

		try {
			params = JSON.parse(uri.query);
		} catch (e) {}

		if (!params || params.isEmpty) {
			return new TextEncoder().encode('');
		}

		return getCodingFileContent(params.fileName, params.commit);
	}
}
