// this file contains the implementation of the standard gulp api
import * as plugins from './smartgulp.plugins.js';
import { GulpStream } from './smartgulp.classes.gulpstream.js';
import { Transform } from 'stream';

import { SmartFile } from '@push.rocks/smartfile';

export let src = (minimatchPathArrayArg: string[]): Transform => {
  let gulpStream = new GulpStream();
  let handleFiles = async () => {
    let smartfileArray: SmartFile[] = [];
    for (let minimatchPath of minimatchPathArrayArg) {
      let localSmartfileArray = await plugins.smartfile.fs.fileTreeToObject(
        process.cwd(),
        minimatchPath
      );
      smartfileArray = [...smartfileArray, ...localSmartfileArray];
    }
    gulpStream.pipeSmartfileArray(smartfileArray);
  };
  handleFiles().catch((err) => {
    console.log(err);
  });
  return gulpStream.stream;
};

export let dest = (dirArg: string) => {
  const stream = new plugins.smartstream.SmartDuplex({
    objectMode: true,
    writeFunction: async (fileArg: SmartFile) => {
      const filePath = plugins.path.join(dirArg, fileArg.relative);
      const dirPath = plugins.path.dirname(filePath);
      await plugins.smartfile.fs.ensureDir(dirPath);
      await plugins.smartfile.memory.toFs(fileArg.contentBuffer, filePath);
    }
  });
  return stream;
};

export let replace = () => {
  const stream = new plugins.smartstream.SmartDuplex({
    objectMode: true,
    writeFunction: async (fileArg: SmartFile) => {
      await fileArg.write();
    }
  });
  return stream;
};
