import {ErrorWithContext} from '@extollo/lib'
import {ShellCommand} from './types'
import {ExecutionResult} from './ExecutionResult'

export class CommandError extends ErrorWithContext {
    public static make(command: ShellCommand, result: ExecutionResult): CommandError {
        const combinedOutput = result.combinedOutput.join(' ').toLowerCase()

        const accessDeniedPhrases = [
            'not permitted',
            'access denied',
            'insufficient permission',
            'permission denied'
        ]

        for ( const phrase of accessDeniedPhrases ) {
            if ( combinedOutput.includes(phrase) ) return new PermissionDeniedError(command, result)
        }

        const notFoundPhrases = [
            'command not found',
        ]

        for ( const phrase of notFoundPhrases ) {
            if ( combinedOutput.includes(phrase) ) return new CommandNotFoundError(command, result)
        }

        const resourceNotFoundPhrases = [
            'no such file',
            'no such directory',
            'no such file or directory',
            'no such directory or file',
        ]

        for ( const phrase of resourceNotFoundPhrases ) {
            if ( combinedOutput.includes(phrase) ) return new FilesystemResourceNotFoundError(command, result)
        }

        return new CommandError(command, result)
    }

    constructor(command: ShellCommand, result: ExecutionResult) {
        super(`Unable to execute command: ${command}`, { command, result })
    }
}

export class PermissionDeniedError extends CommandError {}

export class CommandNotFoundError extends CommandError {}

export class FilesystemResourceNotFoundError extends CommandError {}
