import utils from "../../utils/general-utils";
import { IConfig } from "../../interfaces/config";

export class TableProperty {
    propName: string
    lowerCasePropName: string
    type: string
    isAllowNull: boolean
    isPrimaryKey: boolean
    isAutoIncrement: boolean
    defaultValue: string | number
    isRef: boolean
    isLookup: boolean
    reference?: {
        model: string
        lowerCaseModel: string
        key: string
        isToSelf: boolean
        isMapTable: boolean
    }
    lookup?: {
        tableName: string
        propName: string
    }

    constructor(propertyName, tableName, autoSequelizeTableData, config: IConfig) {
            this.propName = propertyName;
            this.lowerCasePropName = utils.lowerCaseFirstLetter(propertyName);
            this.type = utils.getType(config.DATABASE_CONNECTION_SETINGS[config.ENV].dialect, autoSequelizeTableData[propertyName].type);
            this.isAllowNull = autoSequelizeTableData[propertyName].allowNull || false;
            this.isPrimaryKey = utils.isPrimaryKey(propertyName, autoSequelizeTableData[propertyName].primaryKey, config.ORM_GENERATE.pkIdentifier);
            this.isAutoIncrement = (this.isPrimaryKey || autoSequelizeTableData[propertyName].autoIncrement) ? true : false;
            this.defaultValue = autoSequelizeTableData[propertyName].defaultValue || null;
            this.isRef = autoSequelizeTableData[propertyName].foreignKey && autoSequelizeTableData[propertyName].foreignKey.target_table ? true : false;
            this.isLookup = utils.isLookup(propertyName, config.ORM_GENERATE.lookup);

        if (this.isRef) {
            this.reference = {
                model: autoSequelizeTableData[propertyName].foreignKey.target_table,
                lowerCaseModel: utils.lowerCaseFirstLetter(autoSequelizeTableData[propertyName].foreignKey.target_table), 
                key: autoSequelizeTableData[propertyName].foreignKey.target_column,
                isToSelf: autoSequelizeTableData[propertyName].foreignKey.target_table === tableName,
                isMapTable: utils.isMapTable(tableName, config.ORM_GENERATE.manyToManyIdentifiers)
            }
        } else {
            this.reference = <any>{}
        }

        if (this.isLookup) {
            this.lookup = {
                tableName: config.ORM_GENERATE.lookup.tableName,
                propName: utils.makeLookupPropName(propertyName, config.ORM_GENERATE.lookup)
            }
        }
    }
}