const fs = require('fs-extra')
const Insight = require('../lib/insight')
const importJDL = require('../lib/import-jdl').importJDL

module.exports = async function (context) {
  // grab some features
  const { parameters, print, strings, system } = context
  const { isBlank } = strings

  // validation
  if (isBlank(parameters.first)) {
    print.info(`${context.runtime.brand} generate import-jdl <jdl-filename>\n`)
    print.info('A JDL filename is required.')
    return
  }

  // load the ignite config and set the default jhipster directory
  const jdlFiles = parameters.array
  print.info('The JDL is being parsed.')
  const jhipsterConfig = await fs.readJson(`.jhipster/yo-rc.json`)
  const prodDatabaseType = jhipsterConfig['generator-jhipster'].prodDatabaseType
  const applicationType = jhipsterConfig['generator-jhipster'].applicationType
  const baseName = jhipsterConfig['generator-jhipster'].baseName
  try {
    const importState = importJDL(jdlFiles, prodDatabaseType, applicationType, baseName, print)
    let entityNames = []
    if (importState.exportedEntities.length > 0) {
      entityNames = importState.exportedEntities.map(exportedEntity => exportedEntity.name)
      print.info(`Found entities: ${entityNames.join(', ')}.`)
    } else {
      print.info('No change in entity configurations, no entities were updated.')
    }

    print.success(entityNames)
    // generate update entities
    for (let i = 0; i < entityNames.length; i++) {
      console.log(`ignite g entity ${entityNames[i]}`)
      await system.spawn(`ignite g entity ${entityNames[i]}`, { stdio: 'inherit' })
    }

    print.success(`JDL successfully imported!`)
  } catch (e) {
    print.error('\nError while parsing entities from JDL\n')
    if (e && e.message) {
      print.error(`${e.name || ''}: ${e.message}`)
    }
  }
  Insight.trackGenerator(context, 'import-jdl')
}

@@ -122,16 +122,65 @@
 mportJDL
+%0Aconst generateFiles = require('../entity/files')
 %0A%0Amodule
@@ -250,16 +250,24 @@
  const %7B
+ ignite,
  paramet
@@ -289,16 +289,8 @@
 ings
-, system
  %7D =
@@ -327,16 +327,64 @@
  strings
+%0A  this.igniteConfig = ignite.loadIgniteConfig()
 %0A%0A  // v
@@ -1432,24 +1432,317 @@
  updated.')%0A
+      if (parameters.options.regenerate) %7B%0A        print.info('Regenerate Flag - regenerating all entities')%0A        fs.readdirSync('.jhipster')%0A          .filter(file =%3E file !== 'yo-rc.json')%0A          .forEach(file =%3E %7B%0A            entityNames.push(file.split('.')%5B0%5D)%0A          %7D)%0A      %7D%0A
     %7D%0A%0A    p
@@ -1860,62 +1860,131 @@
     
-console.log(%60ignite g
+this.name =
  entity
- $%7BentityNames%5Bi%5D%7D%60
+Names%5Bi%5D%0A      print.success(%60Generating $%7Bthis.name%7D%60)%0A      await generateFiles(this, context
 )%0A     
+ //
  awa

add regenerate JDL option, call generateFiles instead of ignite