import { Table } from "../classes/Table";
import { IConfig } from "../../interfaces/config";
import * as path from "path";
import * as fse from "fs-extra";
import { CONSTANT } from "../../utils/constants";
import utils from "../../utils/general-utils";
import * as serviceMethodWriter from "./write-service-methods";

export function generate(tables: Array<Table>, config: IConfig) {
    let servicePath = config.ORM_GENERATE.path.services;
    let daosPath = config.ORM_GENERATE.path.daos;
    let pathSplit = daosPath.split("/");
    let modelFolderName = pathSplit[pathSplit.length - 1];

    tables.forEach((x) => {
        const tableName = utils.capitalizeFirstLetter(x.tableName);
        let sFile = "";

        if (servicePath && (fse.pathExistsSync(`${servicePath}/${tableName}.ts`) || fse.pathExistsSync(`${servicePath}/${tableName}.service.ts`))) {
            console.log(tableName + "service.ts encountered. Skipping... no overwrite occurred");
        } else {
            console.log("writing: ", `${servicePath}/${tableName}`)
            
            let sFile = `import {${tableName}} from "../${modelFolderName}/${tableName}"; \n\n\n` +
                        `class ${tableName}Service { \n\n` +
                        `\t${CONSTANT.GENERATED_SERVICE_METHODS} \n` +

                        `${serviceMethodWriter.get(x, config)}` +

                        `\n} \n\n` +
                        `\n\n export default new ${tableName}Service();`;
    
            fse.outputFileSync(`${servicePath}/${tableName}.service.ts`, sFile, "utf8");
    
            sFile = "";
        } 
    });
}

