module.exports = (grunt) ->
  require('load-grunt-tasks')(grunt)

  `const sass = require('sass')`
  `const postcss = require('postcss')`
  `const autoprefixer = require('autoprefixer')`
  `const fs = require('fs')`

  grunt.initConfig
    pkg: grunt.file.readJSON('package.json')
    version_tag: 'v<%= pkg.version %>'
    comments: """
/*!
Chosen, a Select Box Enhancer for jQuery and Prototype
Version <%= pkg.version %>
Full source at https://github.com/jjj/chosen
Copyright (c) 2011-<%= grunt.template.today('yyyy') %> JJJ
MIT License, https://github.com/jjj/chosen/blob/master/LICENSE.md
This file is generated by `grunt build`, do not edit it by hand.
*/
\n
"""
    minified_comments: "/* Chosen <%= version_tag %> | (c) 2011-<%= grunt.template.today('yyyy') %> JJJ | MIT License, https://github.com/jjj/chosen/blob/master/LICENSE.md */\n"

    concat:
      options:
        banner: '<%= comments %>'
      jquery:
        src: ['dist/js/chosen.jquery.js']
        dest: 'dist/js/chosen.jquery.js'
      proto:
        src: ['dist/js/chosen.proto.js']
        dest: 'dist/js/chosen.proto.js'
      css:
        src: ['dist/css/chosen.css']
        dest: 'dist/css/chosen.css'

    copy:
      main:
        src: 'LICENSE.md'
        dest: 'dist/'
      scss:
        files: [
          {expand: true, cwd: 'sass/', src: ['**/*.scss'], dest: 'dist/scss/'}
        ]
      docs:
        files: [
          {expand: true, cwd: 'dist/js/', src: ['*.js'], dest: 'docs/'}
          {expand: true, cwd: 'dist/css/', src: ['*.css', '*.map'], dest: 'docs/'}
          {expand: true, cwd: 'dist/', src: ['LICENSE.md'], dest: 'docs/'}
        ]

    coffee:
      options:
        join: true
      jquery:
        files:
          'dist/js/chosen.jquery.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.jquery.coffee']
      proto:
        files:
          'dist/js/chosen.proto.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.proto.coffee']
      test:
        files:
          'spec/public/jquery_specs.js': 'spec/jquery/*.spec.coffee'
          'spec/public/proto_specs.js': 'spec/proto/*.spec.coffee'

    uglify:
      options:
        banner: '<%= minified_comments %>'
      jquery:
        options:
          mangle:
            reserved: ['jQuery']
        files:
          'dist/js/chosen.jquery.min.js': ['dist/js/chosen.jquery.js']
      proto:
        files:
          'dist/js/chosen.proto.min.js': ['dist/js/chosen.proto.js']

    sass:
      options:
        outputStyle: 'expanded'
        implementation: sass
        sourceMap: true
      chosen_css:
        files:
          'dist/css/chosen.css': 'sass/chosen.scss'

    cssmin:
      options:
        banner: '<%= minified_comments %>'
        keepSpecialComments: 0
      main:
        src: 'dist/css/chosen.css'
        dest: 'dist/css/chosen.min.css'

    watch:
      default:
        files: ['coffee/**/*.coffee', 'sass/*.scss']
        tasks: ['build', 'jasmine']
      test:
        files: ['spec/**/*.coffee']
        tasks: ['jasmine']

    jasmine:
      jquery:
        options:
          vendor: [
            'docs/docsupport/jquery-3.5.1.min.js'
          ]
          styles: [
            'docs/chosen.css'
          ]
          specs: 'spec/public/jquery_specs.js'
          launch:
            args: ['--no-sandbox', '--disable-setuid-sandbox']
            executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined
        src: [ 'docs/chosen.jquery.js' ]
      jquery_old:
        options:
          vendor: [
            'docs/docsupport/jquery-1.12.4.min.js'
          ]
          styles: [
            'docs/chosen.css'
          ]
          specs: 'spec/public/jquery_specs.js'
          launch:
            args: ['--no-sandbox', '--disable-setuid-sandbox']
            executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined
        src: [ 'docs/chosen.jquery.js' ]
      proto:
        options:
          vendor: [
            'docs/docsupport/prototype-1.7.0.0.js'
            'node_modules/simulant/dist/simulant.umd.js'
          ]
          styles: [
            'docs/chosen.css'
          ]
          specs: 'spec/public/proto_specs.js'
          launch:
            args: ['--no-sandbox', '--disable-setuid-sandbox']
            executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined
        src: [ 'docs/chosen.proto.js' ]

  grunt.loadTasks 'tasks'

  grunt.registerTask 'postcss', 'Apply autoprefixer to CSS', ->
    css = fs.readFileSync('dist/css/chosen.css', 'utf8')
    result = postcss([autoprefixer(overrideBrowserslist: ['last 1 version'])]).process(css, from: 'dist/css/chosen.css')
    fs.writeFileSync('dist/css/chosen.css', result.css)
    grunt.log.ok('CSS prefixed with autoprefixer')

  grunt.registerTask 'fix-sourcemaps', 'Fix sourcemap references to be relative', ->
    # Fix dist sourcemap URL reference
    css = fs.readFileSync('dist/css/chosen.css', 'utf8')
    css = css.replace(/\/\*# sourceMappingURL=dist\/css\/chosen\.css\.map \*\/$/, '/*# sourceMappingURL=chosen.css.map */')
    fs.writeFileSync('dist/css/chosen.css', css)

    # Fix dist sourcemap file paths to be relative
    mapContent = fs.readFileSync('dist/css/chosen.css.map', 'utf8')
    mapObj = JSON.parse(mapContent)
    # Replace absolute file:// paths with relative paths
    mapObj.sources = mapObj.sources.map (source) ->
      source.replace(/^file:\/\/\/.*\/sass\//, '../../sass/')
    fs.writeFileSync('dist/css/chosen.css.map', JSON.stringify(mapObj))

    # Fix docs sourcemap URL reference
    css = fs.readFileSync('docs/chosen.css', 'utf8')
    css = css.replace(/\/\*# sourceMappingURL=dist\/css\/chosen\.css\.map \*\/$/, '/*# sourceMappingURL=chosen.css.map */')
    fs.writeFileSync('docs/chosen.css', css)

    # Fix docs sourcemap file paths to be relative
    mapContent = fs.readFileSync('docs/chosen.css.map', 'utf8')
    mapObj = JSON.parse(mapContent)
    mapObj.sources = mapObj.sources.map (source) ->
      source.replace(/^file:\/\/\/.*\/sass\//, '../sass/')
    fs.writeFileSync('docs/chosen.css.map', JSON.stringify(mapObj))

    grunt.log.ok('Fixed sourcemap references')

  grunt.registerTask 'default', ['build']
  grunt.registerTask 'build', ['coffee:jquery', 'coffee:proto', 'sass', 'concat', 'uglify', 'postcss', 'cssmin', 'copy:main', 'copy:scss', 'copy:docs', 'fix-sourcemaps']
  grunt.registerTask 'test',  ['coffee', 'jasmine:jquery', 'jasmine:jquery_old']
  grunt.registerTask 'test:jquery',  ['coffee:test', 'coffee:jquery', 'jasmine:jquery', 'jasmine:jquery_old']
  grunt.registerTask 'test:proto',  ['coffee:test', 'coffee:proto', 'jasmine:proto']


