import * as CommonFunctions from '../common-functions/common-functions';
import * as Models from '../models/models';
import Gherkin from 'gherkin';
import { messages } from 'cucumber-messages';

export class CollectFeatureFiles {
  private featuresDir: string| undefined;

  public constructor( userProperties?: Models.UserProperties ) {
    this.featuresDir = userProperties?.featuresFolder;
  }
  public async collectFeatures(): Promise<messages.IGherkinDocument[] | null> {
    const result = await CommonFunctions.fileSystemFunctions.checkFolder( this.featuresDir );

    if ( ! result ) {
      return [] as messages.IGherkinDocument[];
    }

    const files = await CommonFunctions.fileSystemFunctions.getFilesAsync( this.featuresDir as string );
    const featureFiles = files.filter( ( file ) => file.endsWith( '.feature' ) );

    let features = await Promise.all(
      featureFiles.map( async ( feature ) => {
        const stream = Gherkin.fromPaths( [feature] );
        const gherkinDocument = ( await CommonFunctions.streamFunctions.streamToArrayAsync( stream ) )[1].gherkinDocument as messages.GherkinDocument;
        return gherkinDocument;
      } ),
    );

    features = features.filter( x => x );

    return features?.length > 0 ? features : null;
  }
}

// Type '(IGherkinDocument | null | undefined)[]' is not assignable to type 'IGherkinDocument[]'.
//   Type 'IGherkinDocument | null | undefined' is not assignable to type 'IGherkinDocument'.
//     Type 'undefined' is not assignable to type 'IGherkinDocument'.
