"use strict";

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

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

var _loaderUtils = require("loader-utils");

var _schemaUtils = _interopRequireDefault(require("schema-utils"));

var _SingleEntryPlugin = _interopRequireDefault(require("webpack/lib/SingleEntryPlugin"));

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

/* import WebWorkerTemplatePlugin from 'webpack/lib/webworker/WebWorkerTemplatePlugin';
import ExternalsPlugin from 'webpack/lib/ExternalsPlugin'; */
const schema = {
  type: 'object',
  properties: {
    publicPath: {
      anyOf: [{
        type: 'string'
      }, {
        instanceof: 'Function'
      }]
    },
    filename: {
      anyOf: [{
        type: 'string',
        minLength: 1
      }, {
        instanceof: 'Function'
      }]
    },
    chunkFilename: {
      type: 'string',
      minLength: 1
    },
    esModule: {
      type: 'boolean'
    }
  },
  additionalProperties: false
}; // eslint-disable-next-line

function loader() {}

function getDefaultFilename(filename) {
  if (typeof filename === 'function') {
    return filename;
  }

  return filename.replace(/\.([a-z]+)(\?.+)?$/i, '.worker.$1$2');
}

function getDefaultChunkFilename(chunkFilename) {
  return chunkFilename.replace(/\.([a-z]+)(\?.+)?$/i, '.worker.$1$2');
}

function pitch(request) {
  this.cacheable(false);
  const options = (0, _loaderUtils.getOptions)(this);
  (0, _schemaUtils.default)(schema, options, {
    name: 'Worker Loader',
    baseDataPath: 'options'
  });
  const workerContext = {};
  const compilerOptions = this._compiler.options || {};
  const filename = options.filename ? options.filename : getDefaultFilename(compilerOptions.output.filename);
  const chunkFilename = options.chunkFilename ? options.chunkFilename : getDefaultChunkFilename(compilerOptions.output.chunkFilename);
  const publicPath = options.publicPath ? options.publicPath : compilerOptions.output.publicPath;
  workerContext.options = {
    filename,
    chunkFilename,
    publicPath,
    globalObject: 'self'
  };
  workerContext.compiler = this._compilation.createChildCompiler(`worker-loader ${request}`, workerContext.options);
  /* 
  new WebWorkerTemplatePlugin().apply(workerContext.compiler);
  
  if (compilerOptions.externals) {
    new ExternalsPlugin(
      getExternalsType(compilerOptions),
      compilerOptions.externals
    ).apply(workerContext.compiler);
  } */

  new _SingleEntryPlugin.default(this.context, `!!${request}`, _path.default.parse(this.resourcePath).name).apply(workerContext.compiler);
  workerContext.request = request;
  const cb = this.async();
  workerContext.compiler.runAsChild((errorArg, entries, compilation) => {
    let error = errorArg;

    if (!error && compilation.errors && compilation.errors.length) {
      // eslint-disable-next-line
      error = compilation.errors[0];
    }

    const entry = entries && entries[0] && entries[0].files.values().next().value;

    if (!error && !entry) {
      error = Error(`WorkerPlugin: no entry for ${request}`);
    }

    if (error) {
      return cb(error);
    }

    function workerCode() {
      // if (this.workerInstance) {
      //   return this.workerInstance;
      // }
      let blob;

      try {
        blob = new Blob([`importScripts('${this.workerUrl}');`], {
          type: 'application/javascript'
        });
      } catch (e1) {
        throw new Error(e1);
      }

      const url = window.URL || window.webkitURL;
      const blobUrl = url.createObjectURL(blob); // this.workerInstance = new Worker(blobUrl);
      // return this.workerInstance;

      let worker = new Worker(blobUrl);
      return worker;
    }

    return cb(null, `const workerObj ={\n
      workerInstance: null, \n
			workerUrl: __webpack_public_path__ + ${JSON.stringify(entry)}, \n
			getInstance: ${workerCode} \n
		};\n
    ${options.esModule ? 'export default' : 'module.exports ='} workerObj;
    `); // return cb(
    //   null,
    //   `${options.esModule ? 'export default' : 'module.exports ='} {\n
    //   workerInstance: null, \n
    // 	workerUrl: __webpack_public_path__ + ${JSON.stringify(entry)}, \n
    // 	getInstance: ${workerCode} \n
    // }`
    // );
  });
}