import { Schema as AuthSchemaOptions } from './schema';
import {
  Rule,
  Tree,
  SchematicContext,
  chain,
  mergeWith,
  apply,
  url,
  move,
} from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import {addPackageToPackageJson} from "../utils/json";
import {getProject, Project} from "../utils/project";

let project: Project;

function addDependenciesToPackageJson(options: AuthSchemaOptions) {
  return (host: Tree, context: SchematicContext) => {
    addPackageToPackageJson(host,
      [
        `@ecip/job@1.0.0-rc.1`,
      ],'dependencies')
  };
}

function installPackages(): Rule {
  return (host: Tree, context: SchematicContext) => {
    context.addTask(new NodePackageInstallTask());
    return host;
  };
}


function addFilesToRoot(options: AuthSchemaOptions) {
  return chain([
    mergeWith(
      apply(url('./files'), [
        move(`${project.sourceRoot}/app/routes`),
      ]),
    ),
  ]);
}

export default function(options: AuthSchemaOptions): Rule {
  return (host: Tree, context: SchematicContext) => {
    project = getProject(host, options.project);
    return chain([
      addDependenciesToPackageJson(options),
      addFilesToRoot(options),
      installPackages(),
    ])(host, context);
  };
}
