var path = require("path");
  
module.exports = function(tempFolder, themeScssFilePath, emblaJsOutputPath, emblaCssOutputPath, emblaIconsOutputPath, emblaIconsTemplateOutputPath, emblaIllustrationsOutputPath, emblaIllustrationsTemplateOutputPath) {

  var path = require("path");
  var nodesass = require("node-sass");

  tempFolder = path.resolve(tempFolder);
  var cssMapsFolder = path.resolve(emblaCssOutputPath + "/maps");

  var tempIconsFolder = path.resolve(tempFolder, "temp-icons");
  var tempIllustrationsFolder = path.resolve(tempFolder, "temp-illustrations");

  //Init functions
  function postCss() {
    let autoprefixerBrowser = [
      "Android 2.3",
      "Android >= 4",
      "Chrome >= 20",
      "Firefox >= 24",
      "Explorer >= 8",
      "iOS >= 6",
      "Opera >= 12",
      "Safari >= 6"
    ];

    initResult = {
      "embla-prod": {
        options: {
          map: {
            inline: false, // save all sourcemaps as separate files...
            annotation: cssMapsFolder // ...to the specified directory
          },
          processors: [
            require('pixrem')(), // add fallbacks for rem units
            require('autoprefixer')({ overrideBrowserslist: autoprefixerBrowser }), // add vendor prefixes
            require('cssnano')()// minify the result
          ],
        },
        src: path.resolve(tempFolder + "/*css"),
        dest: path.resolve(emblaCssOutputPath + "/embla.min.css")
      },
      "embla-dev": {
        options: {
          processors: [
            require('pixrem')(), // add fallbacks for rem units
            require('autoprefixer')({ overrideBrowserslist: autoprefixerBrowser }), // add vendor prefixes
          ],
        },
        src: path.resolve(tempFolder + "/*.css"),
        dest: path.resolve(emblaCssOutputPath + "/embla.css")
      }
    };

    return initResult;
  }

  function sass() {
    return {
      "embla-dist": {
        options: {
          implementation: nodesass,
          sourceMap: true,
          includePaths: [
            path.join(__dirname, "../node_modules"),
            path.join(process.cwd(), "node_modules")
          ]
        },
        files: [{
          expand: true,
          cwd: path.resolve(__dirname + "/scss"),
          src: [
            'embla.scss'
          ],
          dest: tempFolder,
          ext: '.css'
        }]
      }
    };
  }

  function scsslint() {
    return {
      "embla-scss-lint": {
        "allFiles": [
          path.resolve(__dirname + '/scss/**/*.scss')
        ],
        options: {
          bundleExec: false,
          config: path.resolve(__dirname + "/.scss-lint.yml"),
          reporterOutput: path.resolve( __dirname + '/scss-lint-report.xml'),
          colorizeOutput: true
        },
      }
    };
  }

  function clean() {
    return {
      "embla-all": [tempFolder, emblaCssOutputPath, emblaIconsOutputPath],
      "embla-temp": [tempFolder],
      "embla-dist": ['dist'],
      "docs": ['docs/assets'],
      'embla-icons-with-old-name': {
        src: [path.resolve(__dirname + '/icons/**/*.svg')],
        filter: function(filepath) {
          //Delete forms icons - only here to make it easier to export from Sketch
          if( filepath === 'icons/checkbox-off.svg' ||
              filepath === 'icons/checkbox-on.svg' ||
              filepath === 'icons/radio-off.svg' ||
              filepath === 'icons/radio-on.svg' ||
              filepath === 'icons/switch-on.svg' ||
              filepath === 'icons/switch-off.svg' ||
              filepath === 'icons/toggle-on.svg'||
              filepath === 'icons/toggle-off.svg'){
            return true;
          }
          return filepath.startsWith('icons/ ');
        },
      }
    };
  }

  function mkdir() {
    return {
      "embla-all": {
        options: {
          mode: 0777 & (~process.umask()),
          create: ['dist']
        },
      }
    };
  }

  function jshint() {
    return {
      "embla-jshint": {
        options: {
          curly: true,
          eqeqeq: true,
          eqnull: true,
          browser: true,
          globals: {
            //jQuery: true
          },
          esversion: 6
        },
        uses_defaults: [path.resolve(__dirname + '/js/**/*.js')],
      }
    };
  }

  function concat() {
    return {
      "embla-dist": {
        options: {
          separator: ';',
        },
        src: [
          path.resolve(__dirname + '/js/embla.js')
        ],
        dest: path.resolve(emblaJsOutputPath + '/embla.js'),
      }
    };
  }

  function copy() {
    return {
      "embla-sprite-to-output": {
        files: [
          {expand: true, cwd: path.resolve(tempIconsFolder + '/symbol/svg/'), src: ["sprite.symbol.svg"], dest: path.resolve(emblaIconsOutputPath), filter: 'isFile'},
        ]
      },
      "embla-illustrations-sprite-to-output": {
        files: [
          {expand: true, cwd: path.resolve(tempIllustrationsFolder + '/symbol/svg/'), src: ["sprite.symbol.svg"], dest: path.resolve(emblaIllustrationsOutputPath), filter: 'isFile'},
        ]
      },
      "embla-icons-template": {
        files: [
          {expand: true, cwd: path.resolve(tempIconsFolder + '/symbol/'), src: ["sprite.symbol.html"], dest: path.resolve(emblaIconsTemplateOutputPath), filter: 'isFile'},
        ]      
      },
      "embla-illustrations-template": {
        files: [
          {expand: true, cwd: path.resolve(tempIllustrationsFolder + '/symbol/'), src: ["sprite.symbol.html"], dest: path.resolve(emblaIllustrationsTemplateOutputPath), filter: 'isFile'},
        ]      
      },
      "embla-rename-sketch-icons": {
        expand: true,
        flatten: true,
        src: [path.resolve(__dirname, "sketch-icons/**/*.svg")],
        dest: path.resolve(tempIconsFolder + "/renamed-icons/"),
        nonull: false,
        filter: function(filepath) {

          
          //Don't copy unintentional sketch icons
          if( 
            filepath.indexOf("checkbox - off.svg") > 0 ||
            filepath.indexOf("checkbox - on.svg") > 0  ||
            filepath.indexOf("checkbox - off - intermediate.svg") > 0 ||
            filepath.indexOf("checkbox - on - intermediate.svg") > 0  ||
            filepath.indexOf("radio - off.svg") > 0  ||
            filepath.indexOf("radio - on.svg") > 0  ||
            filepath.indexOf("switch - off.svg") > 0  ||
            filepath.indexOf("switch - on.svg") > 0
            ) 
          {
            return false;
          }

          return true;
        },
        rename: function(dest, src) {
          let file = src.replace(/^ /, '').replace(' - ','-').replace(' ','-').toLowerCase();
          return dest + "/" + file;
        }
      },
      "embla-rename-sketch-illustrations": {
        expand: true,
        flatten: true,
        src: [path.resolve(__dirname, "sketch-illustrations/**/*.svg")],
        dest: path.resolve(tempIllustrationsFolder + "/renamed-illustrations/"),
        nonull: false,
        filter: function(filepath) {
          return true;
        },
        rename: function(dest, src) {
          let file = src.replace(/^ /, '').replace(' - ','-').replace(' ','-').toLowerCase();
          return dest + "/" + file;
        }
      },
      "embla-scss-theme-variables": {
        files: [
          {src: [themeScssFilePath], dest: path.resolve(__dirname + "/scss/theme-variables.scss"), filter: 'isFile'},
        ]
      },
      "embla-scss-theme-variables-clean": {
        files: [
          {src: [path.resolve(__dirname + "/scss/theme-variables-clean.scss")], dest: path.resolve(__dirname + "/scss/theme-variables.scss"), filter: 'isFile'},
        ]
      }
    };
  }

  function svgmin() {
    return {
      "embla-optimized-icons": {
        expand: true,
        flatten: true,
        cwd: path.resolve(tempIconsFolder, "renamed-icons"),
        src: ["*.svg"],
        dest: path.resolve(tempIconsFolder, "optimized-icons")
      },
      "embla-optimized-illustrations": {
        expand: true,
        flatten: true,
        cwd: path.resolve(tempIllustrationsFolder, "renamed-illustrations"),
        src: ["*.svg"],
        dest: path.resolve(tempIllustrationsFolder, "optimized-illustrations")
      }
    }
  }

  function svgSprite() {
    return {
      "embla-icons-to-sprite": {
        expand: true,
        flatten: true,
        cwd: path.resolve(tempIconsFolder, "optimized-icons"),
        src: ["*.svg"],
        dest: tempIconsFolder,
        options: {
          mode: {
            symbol: {
              example: {
                template: path.resolve(__dirname, "build-helpers/icons-sprite-symbol-html-template.html")
              }
            }
          },
          svg: {
            transform: function(svg) {
              //Remove fills, so we can style in css
              let newSvg = svg.replace(/\s(fill="((#.{3,6})|(none))")/g, "");
              return newSvg;
            }
          }
        }
      },
      "embla-illustrations-to-sprite": {
        expand: true,
        flatten: true,
        cwd: path.resolve(tempIllustrationsFolder, "optimized-illustrations"),
        src: ["*.svg"],
        dest: tempIllustrationsFolder,
        options: {
          mode: {
            symbol: {
              example: {
                template: path.resolve(__dirname, "build-helpers/illustrations-sprite-symbol-html-template.html")
              }
            }
          },
          svg: {
            transform: function(svg) {
              //Remove fills, so we can style in css
              let newSvg = svg.replace(/\s(fill="((#.{3,6})|(none))")/g, "");
              
              //Remove masks from sketch export (remove when SMMA/MON fix sketch illustrations)
              newSvg = newSvg.replace(/<mask(.*?)<\/mask>/g, "");
              newSvg = newSvg.replace(/<g mask="(.*?)<\/g>/g, "");

              return newSvg;
            }
          },
          shape: {
            transform: [
              {
                svgo: {
                  plugins: [
                    { cleanupIDs: { prefix: "i-" }}
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }

  function webpack() {
    var webpack = require("webpack");
    var path = require("path");
    var UglifyJsPlugin = require("uglifyjs-webpack-plugin");
    var WebpackNotifierPlugin = require('webpack-notifier');

    //See https://github.com/webpack/css-loader/issues/145
    require("es6-promise").polyfill();

    return {
      options: {
        cache: false,

        stats: {
          colors: false,
          modules: false,
          reasons: true
        },

        storeStatsTo: "webpackStats",

        progress: false,

        // Enable sourcemaps for debugging webpack's output.
        devtool: "source-map",

        resolve: {
          modules: [
            path.resolve(__dirname),
            "node_modules",
          ],
          alias: {
          },
          // Add '.ts' and '.tsx' as resolvable extensions.
          extensions: [".webpack.js", ".web.js", ".js", ".ts", ".tsx"]
        },

        module: {
          rules: [
            {
              test: /\.css$/,
              use: [
                  "style-loader",
                  "css-loader"
              ]
            },
            { 
              test: /bootstrap-sass\/assets\/javascripts\//, 
              use: 'imports-loader?jQuery=jquery' 
            },
            {
              test: /\.tsx?$/,
              use: "ts-loader"
            }
          ],
        },

        plugins: [
          new WebpackNotifierPlugin({alwaysNotify: true}),
        ],

        entry: {
          embla: [path.resolve(__dirname + "/ts/embla")],
        },

        output: {
          filename: "[name].js",
          path: emblaJsOutputPath,
          library: "embla",
          libraryTarget: "umd"
        },

        externals: {
          "jquery": "jQuery"
        }
      },

      "embla-build-dev": {
     
        plugins: [
          new webpack.DefinePlugin({
            __DEV__: 'true',
            __TEST__: 'false',
            __PRODUCTION__: 'false'
          })
        ],

        devtool: "source-map",
      },

      "embla-build-production": {
       
        plugins: [
          //new UglifyJsPlugin(),
          new webpack.DefinePlugin({
            __DEV__: 'false',
            __TEST__: 'false',
            __PRODUCTION__: 'true',
            "process.env": { NODE_ENV: JSON.stringify("production") }
          }),
        ],

        devtool: "source-map",
      }

    };
  }

  function replace(){

    let defaultFill = "fill=\"#333333\""

    return {
      'replace-in-icons-cross-gray': {
        src: [path.resolve(__dirname + '/sketch-icons/remove.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/cross-gray.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#B8B8B8"'
        }]
      },
      'replace-in-icons-cross-black': {
        src: [path.resolve(__dirname + '/sketch-icons/remove.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/cross-black.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#000000"'
        }]
      },
      'replace-in-icons-check-mark': {
        src: [path.resolve(__dirname + '/sketch-icons/success.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/check-mark.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#FFFFFF"'
        }]
      },
      'replace-in-icons-success-dark': {
        src: [path.resolve(__dirname + '/sketch-icons/success.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/success-dark.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#71DC9C"'
        }]
      },
      'replace-in-icons-danger-dark': {
        src: [path.resolve(__dirname + '/sketch-icons/danger.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/danger-dark.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#FC7E7A"'
        }]
      },
      'replace-in-icons-warning-dark': {
        src: [path.resolve(__dirname + '/sketch-icons/warning.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/warning-dark.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#F3D15D"'
        }],
      },
      'replace-in-icons-arrow-down': {
        src: [path.resolve(__dirname + '/sketch-icons/arrow down.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/arrow-down.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#555"'
        }],
      },
      'replace-in-icons-arrow-right': {
        src: [path.resolve(__dirname + '/sketch-icons/arrow right.svg')],
        dest: path.resolve(emblaIconsOutputPath + '/arrow-right.svg'),
        replacements: [{
          from: defaultFill,                   // string replacement
          to: 'fill="#555"'
        }],
      }
    };
  }


  return {
      postcss: postCss(),
      scsslint: scsslint(),
      sass: sass(),
      clean: clean(),
      mkdir: mkdir(),
      jshint: jshint(),
      concat: concat(),
      copy: copy(),
      svgmin: svgmin(),
      svg_sprite: svgSprite(),
      webpack: webpack(),
      replace: replace(),
  }
}