const data = require('./data');

for (const item of data) {
  const tpls = [
    "import { IncrementIdEntity } from 'src/common/entity/increment-id.entity';",
    "import { Column, Entity } from 'typeorm';",
    '',
  ];
  const [tableAttrs, ...column] = item.trim().replace(/\n+/, '\n').split('\n');

  const [table, annotate] = handleAttrs(tableAttrs);
  if (annotate) tpls.push('/**', ' * ' + annotate, ' */');

  tpls.push('@Entity()', `export class ${table} extends IncrementIdEntity {`);

  for (let i = 0, attrs; (attrs = column[i]); i++) {
    const [key, type, comment] = handleAttrs(attrs);
    const options = [];
    if (/[A-Z]/g.test(key)) options.push(`name: '${handleName(key)}'`);
    if (comment) options.push(`comment: '${comment}'`);

    if (i) tpls.push('');

    tpls.push(
      `  @Column(${options.length ? `{ ${options.join(', ')} }` : ''})`,
      `  ${key}: ${type};`,
    );
  }

  output(table, tpls.concat('}\n').join('\n'));
}

function handleAttrs(str) {
  return str.trim().split(/\s+/);
}

function output(table, tpl) {
  const fs = require('fs');
  const path = __dirname + '/entity';
  if (!fs.existsSync(path)) fs.mkdirSync(path);
  fs.writeFile(path + `/${handleName(table, '-')}.entity.ts`, tpl, (err) => {
    if (err) {
      console.log(err);
      throw err;
    }

    console.log('【', table, '】转换成功');
  });
}

function handleName(name, sep = '_') {
  if (!name) return;

  return (
    name[0].toLowerCase() +
    name.substr(1).replace(/([A-Z])/g, (m, p) => sep + p.toLowerCase())
  );
}
