/*
 * Copyright (C) 2021 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {mapNotNil} from '../util.js';
import {definitionsOf, isLightweightClass} from '../ast-util.js';
import {lightweightProjectFromPath} from '../easy-ast.js';
import {LightweightClassDefinition} from './lightweight-class-definition.js';
import {LightweightDefinition} from './lightweight-definition.js';

/**
 * Build an index for a lightweight project
 */
function buildIndex(project: LightweightProject): Record<string, string> {
  return Object.fromEntries(
    Object.entries(project).flatMap(([file, definitions]) =>
      Object.keys(definitions).map(definition => [definition, file.toString()]),
    ),
  );
}

/**
 * A lightweight definition class for more advanced use cases
 */
export class LightweightProjectWithIndex {
  /**
   * All definitions
   */
  readonly definitions: Record<string, LightweightDefinition>;

  /**
   * Project
   */
  readonly files: LightweightProject;

  /**
   * Index of all definitions to their respective files
   */
  readonly index: {
    [definitionName: string]: string;
  };

  constructor(project: LightweightProject | string) {
    this.files = typeof project === 'string' ? lightweightProjectFromPath(project) : project;
    this.index = buildIndex(this.files);
    this.definitions = definitionsOf(this.files);
  }

  /**
   * Apply inherited classes; default deeply
   */
  applyInheritance(classLike: LightweightClassDefinition, deep?: boolean): LightweightDefinition {
    return Object.assign(
      mapNotNil(
        [...(classLike.implementedDefinitions ?? []), ...(classLike.extendedDefinitions ?? [])],
        extension => {
          const object = this.definitions[extension.referenceName ?? ''];

          return (deep ?? true) && isLightweightClass(object)
            ? this.applyInheritance(object)
            : JSON.parse(JSON.stringify(object));
        },
      ),
      JSON.parse(JSON.stringify(classLike)),
    );
  }

  /**
   * Instantiate a definition
   *
   * Requires the program to be run with `--require ts-node/register`
   */
  async instantiateDefinitionByName<T>(name: string, findCompiledModule = true): Promise<T | undefined> {
    const fsPath = this.index[name];
    if (fsPath === undefined) {
      return undefined;
    }

    const module = await import(findCompiledModule ? `${fsPath.replace(/\.d\.ts$/, '')}.js` : fsPath);

    return new module[name]() as T;
  }
}

export interface LightweightFile {
  [definitionName: string]: LightweightDefinition;
}

export interface LightweightProject {
  [sourcePath: string]: LightweightFile;
}
