"use strict";

var _path = _interopRequireDefault(require("path"));

var _fs = _interopRequireDefault(require("fs"));

var _utils = require("../utils");

var _logger = require("../logger");

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

const options = (0, _utils.getOptions)();
const {
  cssSelectorZipPath
} = options.impactService;

const zipname = _path.default.parse(cssSelectorZipPath).name; // TODO:NOTE: need to check about .. path related files creation 
// for now  no css files have given  form react-cli need to make sure about it.  


const zippath = _path.default.join(process.cwd(), cssSelectorZipPath);

if (_fs.default.existsSync(_path.default.join(process.cwd(), cssSelectorZipPath))) {
  _fs.default.rmSync(zippath);

  (0, _logger.messageLogger)('zip file deleted', zippath); // fs.rmSync(zippath, {force:true})
} // const minicssComment =
//   '// extracted by mini-css-extract-plugin\n';


const startStr = '// extracted by mini-css-extract-plugin\n' + 'module.exports = ';

module.exports = function (source) {
  const {
    rootContext,
    resourcePath
  } = this;

  const relativePath = _path.default.relative(rootContext, resourcePath);

  const fpath = _path.default.join(rootContext, zipname, relativePath);

  const originalpath = _path.default.join(rootContext, relativePath);

  if (relativePath.startsWith('..')) {
    throw `unexpected path ${relativePath}`;
  }

  const dpath = fpath.slice(0, fpath.lastIndexOf(_path.default.sep));

  if (!_fs.default.existsSync(originalpath)) {
    throw `originalpath not exixt ${originalpath}`;
  }

  if (!_fs.default.existsSync(dpath)) {
    _fs.default.mkdirSync(dpath, {
      recursive: true
    });
  }

  let jsonStr = '{}';

  if (source.startsWith(startStr)) {
    // source will  be  like 
    // `// extracted by mini-css-extract-plugin\nmodule.exports = {"app":"zd-app"};`
    jsonStr = source.slice(startStr.length, -1);
  }

  _fs.default.writeFileSync(`${fpath}_map`, jsonStr);

  _fs.default.writeFileSync(fpath, _fs.default.readFileSync(originalpath));

  return source;
};