/**
 * React Starter Kit (http://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2015 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import browserSync from 'browser-sync';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfigs from './webpack.config.production';
import run from './run';
import path from 'path';
import copyIndex from './copy-index';

global.WATCH = true;
const webpackConfig = webpackConfigs[0]; // Client-side bundle configuration 
const bundler = webpack(webpackConfig);

/**
 * Launches a development web server with "live reload" functionality -
 * synchronizing URLs, interactions and code changes across multiple devices.
 */
async function start() {
  //await run(require('./build'));
  copyIndex();
  await run(require('./serve'));

  await new Promise(resolve => {
    browserSync({
      port: 3005,
      proxy: {
        target: 'localhost:3100',
        //   baseDir: "../build/public/",
        middleware: [
          webpackDevMiddleware(bundler, {
            // IMPORTANT: dev middleware can't access config, so we should
            // provide publicPath by ourselves
            publicPath: webpackConfig.output.publicPath,

            // Pretty colored output
            stats: webpackConfig.stats,

            // For other settings see
            // http://webpack.github.io/docs/webpack-dev-middleware.html
          }),

          // bundler should be the same as above
          webpackHotMiddleware(bundler),
        ],
        // proxyRes: [
        //     function (res, req) {
        //         res.headers["Access-Control-Allow-Origin"] = "*"; 
        //         res.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept"; 
        //         res.headers["Access-Control-Allow-Methods"] = "PUT,POST,GET,DELETE,OPTIONS"; 
        //     }
        // ]
      },
      // no need to watch '*.js' here, webpack will take care of it for us,
      // including full page reloads if HMR won't work
      files: [
        '../build/public/img/*.*',
        '../build/public/fonts/*.*',
        '../build/public/**/*.css',
        '../build/public/js/**/*.*',
        '../build/public/**/*.html',
        '../build/content/**/*.*',
        '../build/templates/**/*.*'
      ]
    }, resolve);
  })
}

export default start;