import fs from 'fs';
import path from 'path';
import { workspace, WorkspaceConfiguration } from 'vscode';

export function getWorkspaceFolder() {
  return workspace.workspaceFolders && workspace.workspaceFolders.length === 1
    ? workspace.workspaceFolders[0].uri.fsPath
    : undefined;
}

export function getProjectFolder(config?: WorkspaceConfiguration, workspaceFolder?: string) {
  if (!config) {
    config = workspace.getConfiguration('sculpt-ui');
  }
  let folder = workspaceFolder || getWorkspaceFolder();
  const folderForStarting = config.get<string>('folderForStarting');
  if (folderForStarting) {
    folder = folder ? path.join(folder, folderForStarting) : folderForStarting;
  }
  return folder;
}

export function isWorkspacesRoot(folder: string) {
  try {
    const packageJson = JSON.parse(fs.readFileSync(path.join(folder, 'package.json'), 'utf8'));
    return !!packageJson.workspaces;
  } catch (e) {
    return false;
  }
}

export function traverseSubFolders(
  parentFolder: string,
  callbackShouldAbort: (path: string) => boolean,
  maxFolderDepth: number = 2,
  excludedFolderNames?: string[],
) {
  let subDirs: string[] = [parentFolder];
  for (let depth = 1; depth <= maxFolderDepth; depth++) {
    const nextSubDirs: string[] = [];
    if (
      subDirs.some(subDir => {
        const files = fs.readdirSync(subDir, { withFileTypes: true });
        return files.some(file => {
          try {
            if (
              file.isDirectory() &&
              (!excludedFolderNames ||
                !excludedFolderNames.some(exclude => exclude.toLowerCase() === file.name.toLowerCase()))
            ) {
              const nextSubDir = path.join(subDir, file.name);
              if (callbackShouldAbort(nextSubDir)) {
                return true;
              }
              nextSubDirs.push(nextSubDir);
            }
          } catch (err) {
            console.error('Error traversing folder ' + file, err);
          }
          return false;
        });
      })
    ) {
      break;
    }
    subDirs = nextSubDirs;
  }
}

export function removeRootFolder(path: string, rootPath: string): string {
  if (path.toLowerCase().indexOf(rootPath.toLowerCase()) === 0) {
    return path.substring(rootPath.length);
  }
  return path;
}
