import * as path from "path";
import * as fse from "fs-extra";
import utils from "../../utils/general-utils";
import { IConfig } from "../../interfaces/config";
import { Table } from "../classes/Table";

export function generate(tables: Array<Table>, config: IConfig) {
    fse.removeSync(path.join(config.ORM_GENERATE.path.interface));

    let sFile = "";

    let interfaceFilePath = path.join(config.ORM_GENERATE.path.interface);

    // sFile += `// this type exists for properties that are intuitively dates but need to be strings for sql server datetime - JS date issue \n`;
    // sFile += `// so you can use date intellisense if the value is a date client-side \n`
    // sFile += `export type StringOrDate = string | Date\n\n`;

    tables.forEach((x) => {
        sFile += `\nexport interface ${utils.capitalizeFirstLetter(x.tableName)} { \n`;

        x.properties.forEach((y) => {
            if (y.isLookup) {
                sFile += `\t${y.lowerCasePropName}?: ${y.type}; \n`;
                sFile += `\t${y.lookup.propName}?: ${y.lookup.tableName}; \n`;
            } else {            
                const isCaseSensitiveMatch = config.ORM_GENERATE.caseSensitiveProps.find((x) => x === y.propName);
                
                if (isCaseSensitiveMatch) {
                    sFile += `\t${y.propName}: ${y.type};\n\n`;
                } else {
                    sFile += `\t${y.lowerCasePropName}?: ${y.type}; \n`;
                }
            }

            /* handle refs */
            // if (y.isRef && !y.isToSelf) {
            //     sFile += `\t${y.reference.lowerCaseModel}?: ${y.reference.model}; \n`;
            // }

        });
        sFile += `\n\t/* ${x.tableName} ref properties */\n`;
        sFile += "}\n";
    });

    // go through again and add one-to-many props
    // aTables.forEach((x) => {
    //     x.properties.forEach((y) => {
    //         if (y.isRef && !y.isToSelf) {
    //             const placeholder = `/* ${x.tableName} ref properties */`;
    //             const propertyStatement = `${placeholder} \n\t${utils.pluralize(y.reference.lowerCaseModel)}?: Array<${y.reference.model}>;`;

    //             if (sFile.indexOf(placeholder) > -1) {
    //                 sFile = sFile.replace(placeholder, propertyStatement);
    //             }
    //         }
    //     })
    // })

    fse.outputFileSync(interfaceFilePath, sFile, "utf8");
}

