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";
import {insertContent, MODULE_ROUTE_CONTENTS, routeModules, routingModuleContent} from "../utils/content";

let project: Project;

function addDependenciesToPackageJson(options: AuthSchemaOptions) {
  return (host: Tree, context: SchematicContext) => {
    addPackageToPackageJson(host,
      [
        `@ecip/auth@1.0.0-rc.1`,
      ],'dependencies')
  };
}

function overwriteRoutingModule(options: AuthSchemaOptions) {
  return (tree: Tree, context: SchematicContext) => {
    // 读取文件内容
    console.log(options);
    const routingModule = tree.get(`${project.sourceRoot}/app/routes/routes-routing.module.ts`)
    if (routingModule) {
      return;
    }
    const content = routingModule.content.toString().replace('// business替换，请勿删除',
      `${options.business}\n\t\t\t// business替换，请勿删除`);
    tree.delete(`${project.sourceRoot}/app/routes/routes-routing.module.ts`);

    tree.create(`${project.sourceRoot}/app/routes/routes-routing.module.ts`, content);
  };
}

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([
      overwriteRoutingModule(options),
      addDependenciesToPackageJson(options),
      addFilesToRoot(options),
      installPackages(),
    ])(host, context);
  };
}
