import gulp from 'gulp';
import browser from 'browser-sync';
import webpack from 'webpack';

import webpackDevMiddleware from 'webpack-dev-middleware';

import webpackHotMiddleware from 'webpack-hot-middleware';

import { config } from './webpack';

import { serveHTML } from './serve-html';

import { servePHP } from './serve-php';

import { serveImages } from './serve-images';

import { serveOur, serveRoot } from './serve-source';

import { serveCoreCSS } from './serve-css--core';

import { serveMainCSS } from './serve-css--main';

const bs = browser.create();

const bundler = webpack(config);
// import modRewrite from 'connect-modrewrite';

export function server () {
    bs.init({
        // server: '../wp-content/themes/biuro',
        proxy: 'https://dev.biuro.lt',
        httpModule: 'http2',
        https: true,
        // https: {
        //     key: '../../certs/dev/privkey.pem',
        //     // cert: '../../certs/live/dev.biuro.lt/certificate.pem'
        //     cert: '../../certs/dev/fullchain.crt'
        // },
        host: 'dev.biuro.lt',
        open: false,
        port: 2000,
        ui: false,
        middleware: [
            webpackDevMiddleware(bundler, { /* options */
                publicPath: '../wp-content/themes/biuro'
            }),
            webpackHotMiddleware(bundler)
            // modRewrite([
            //   '^[^\\.]*$ /index.html [L]',
            //   // '^/wp-json/our-wp-api/v1/(.*)$ https://town.ourdemo.eu/wp-json/our-wp-api/v1/$1 [P]',
            //   // '^http://town.loc.al/wp-content/uploads/2018/03/(.*)$ https://town.ourdemo.eu/wp-content/uploads/2018/03/$1 [P]',
            // ]),
        ]
    });

    gulp.watch('./i/**/*.*', { usePolling: true }, gulp.series(serveImages));

    gulp.watch(['./source/biuro/**/*.*', './source/root/**/*.*'], { usePolling: true }, gulp.series(serveOur, serveRoot));

    gulp.watch('./php/**/*.php', { usePolling: true }, gulp.series(servePHP));

    // gulp.watch(['./*.html', './source/**/*.*', '!./source/biuro/**/*.*', '!./source/root/**/*.*', '../wp-content/themes/biuro/css/core.min.css'], gulp.series(serveHTML));
    gulp.watch(['./source/**/*.*', '!./source/biuro/**/*.*', '!./source/root/**/*.*', '../wp-content/themes/biuro/css/core.min.css'], { usePolling: true }, gulp.series(servePHP));

    gulp.watch(['./*.html', './source/content/*.*', '../wp-content/themes/biuro/css/core.min.css'], { usePolling: true }, gulp.series(serveHTML));

    gulp.watch(['./css/**/*.css'], { usePolling: true }, gulp.parallel(serveCoreCSS, serveMainCSS));

    gulp.watch('../wp-content/themes/biuro/**/*.php').on('change', () => bs.reload());

    gulp.watch('../wp-content/themes/biuro/js/*.js').on('change', () => bs.reload());

    gulp.watch('../wp-content/themes/biuro/css/main.min.css').on('change', () => bs.reload('*.css'));
}
