"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _fs() {
  const data = require("fs");

  _fs = function _fs() {
    return data;
  };

  return data;
}

function _path() {
  const data = require("path");

  _path = function _path() {
    return data;
  };

  return data;
}

var _insertComponent = _interopRequireDefault(require("./sdk/insertComponent"));

var _constants = require("./sdk/constants");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const debug = require('debug')('umi-build-dev:appendBlockToContainer');

function findIndexFile(dir) {
  if ((0, _fs().existsSync)((0, _path().join)(dir, 'index.js'))) return (0, _path().join)(dir, 'index.js');
  if ((0, _fs().existsSync)((0, _path().join)(dir, 'index.jsx'))) return (0, _path().join)(dir, 'index.jsx');
  if ((0, _fs().existsSync)((0, _path().join)(dir, 'index.tsx'))) return (0, _path().join)(dir, 'index.tsx');
  if ((0, _fs().existsSync)((0, _path().join)(dir, 'index.ts'))) return (0, _path().join)(dir, 'index.ts');
}

var _default = ({
  entryPath,
  blockFolderName,
  dryRun,
  index
}) => {
  debug('start to update the entry file for block(s) under the path...');
  const oldEntry = (0, _fs().readFileSync)(entryPath, 'utf-8');
  debug(`insert component ${blockFolderName} with index ${index}`);
  const absolutePath = findIndexFile((0, _path().join)((0, _path().dirname)(entryPath), blockFolderName));
  const blockContent = (0, _fs().readFileSync)(absolutePath, 'utf-8');
  const newEntry = (0, _insertComponent.default)(oldEntry, {
    identifier: blockFolderName,
    relativePath: `./${blockFolderName}`,
    absolutePath,
    isExtractBlock: blockContent.includes(_constants.INSERT_BLOCK_PLACEHOLDER) || blockContent.includes(_constants.UMI_UI_FLAG_PLACEHOLDER),
    index
  });

  if (!dryRun) {
    (0, _fs().writeFileSync)(entryPath, newEntry);
  }
};

exports.default = _default;