require "sass"

module Engines
  class Bootstrap
    DEFAULT_COLORS = ["#D4D8D1", "#A8A8A1", "#AA9A66", "#B74934", "#577492", "#67655D", "#332C2F"]
    MAX_COLORS = DEFAULT_COLORS.length

    @@sass = nil
    attr_reader :colors

    class << self
      def extract_colors(image_url)
        colors = []

        if image_url.blank?
          colors = DEFAULT_COLORS.dup
        else
          begin
            extractor = Prizm::Extractor.new(image_url)
            colors = extractor.get_colors(7, false).sort { |a, b| b.to_hsla[2] <=> a.to_hsla[2] }.map { |p| extractor.to_hex(p) }
            extractor = nil

            # Fill in default colors if parsed colors are less than 7
            if (length = colors.length) < MAX_COLORS
              colors[length...MAX_COLORS] = DEFAULT_COLORS.dup[length...MAX_COLORS]
            end
          rescue
            colors = DEFAULT_COLORS.dup
          end
        end

        colors
      end

      def bootstrap_variables
        @@default_variables ||= File.read("#{Rails.root.to_s}/css/bootstrap-3.3.4/bootstrap/_variables.scss")
      end

      def bootstrap_sass
        return @@sass if @@sass

        @@sass = ''
        mixins = [
          'hide-text', 'opacity', 'image', 'labels', 'reset-filter', 'resize', 'responsive-visibility',
          'size', 'tab-focus', 'text-emphasis', 'text-overflow', 'vendor-prefixes',
          'alerts', 'buttons', 'panels', 'pagination', 'list-group', 'nav-divider',
          'forms', 'progress-bar', 'table-row', 'background-variant', 'border-radius', 'gradients',
          'clearfix', 'center-block', 'nav-vertical-align', 'grid-framework', 'grid'
        ]

        mixins.each do |mixin|
          @@sass += File.read("#{Rails.root.to_s}/css/bootstrap-3.3.4/mixins/_#{mixin}.scss")
        end

        names = [
          'normalize', 'print', 'glyphicons',
          'scaffolding', 'type', 'code', 'grid', 'tables', 'forms', 'buttons',
          'component-animations', 'dropdowns', 'button-groups', 'input-groups',
          'navs', 'navbar', 'breadcrumbs', 'pagination', 'pager', 'labels', 'badges', 'jumbotron',
          'thumbnails', 'alerts', 'progress-bars', 'media', 'list-group', 'panels',
          'responsive-embed', 'wells', 'close',
          'modals', 'tooltip', 'popovers', 'carousel', 'utilities', 'responsive-utilities'
        ]

        names.each do |filename|
          @@sass += File.read("#{Rails.root.to_s}/css/bootstrap-3.3.4/bootstrap/_#{filename}.scss")
        end

        @@sass
      end
    end

    def initialize(colors = [])
      @colors = colors
    end

    def variables
      @variables ||= set_variables
    end

    def compile
      Sass::Engine.new("/* CSS generated by http://lavishbootstrap.com */\n" +
        variables + self.class.bootstrap_sass, syntax: :scss).render
    end

    private

    def set_variables
      @variables = self.class.bootstrap_variables
      @variables.gsub!(/(\$body-bg:\s+)[^;]+/i, '\1' + colors[0].downcase)
      @variables.gsub!(/(\$gray-lighter:\s+)[^;]+/i, '\1' + colors[1].downcase)
      @variables.gsub!(/(\$gray-light:\s+)[^;]+/i, '\1' + colors[2].downcase)
      @variables.gsub!(/(\$gray:\s+)[^;]+/i, '\1' + colors[3].downcase)
      @variables.gsub!(/(\$gray-dark:\s+)[^;]+/i, '\1' + colors[5].downcase)
      #variables.gsub!(/(@gray-darker:\s+)[^;]+/i, '\1' + @colors[6].downcase)

      @variables.gsub!(/(\$brand-primary:\s+)[^;]+/i, '\1' + colors[4].downcase)
      @variables.gsub!(/(\$navbar-inverse-bg:\s+)[^;]+/i, '\1' + colors[6].downcase)
      @variables.gsub!(/(\$table-border-color:\s+)[^;]+/i, '\1' + colors[5].downcase)
    end
  end
end