require File.expand_path('../boot', __FILE__)

#require 'rails/all'
require 'rails'
#require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
#require 'active_resource/railtie'
require 'rails/test_unit/railtie'
require 'sprockets/railtie'
require 'net/http' # lib/mozo/broadcaster/faye.rb

# custom override hack for the couchbase-setting gem, needs to be loaded before other gems, is settings only without dependencies
#require File.expand_path('./../../lib/couchbase-setting', __FILE__)

Bundler.require(*Rails.groups(assets: %w[development test user_app]))
Bundler.require(:assets) if ENV['DEPLOY'] == 'yes'

#NOTE: the JSON.create_id getter/setter has been moved to Thread.current implementation which
# leads to "json_class" fallbacks for created threads. Maybe this will be fixed for future
# rails versions. Current is: 6.1.3.1
# For now make the getter Thread universal, not safe
module JSON
  def self.create_id
    'ruby_class'
  end
end

# URI.escape was deprecated, use CGI escape insted. This is for the version of paperclip still using the URI variant
# If the testsuite runs without this code, please remove it
module URI
  def self.escape(*args)
    CGI.escape(*args)
  end
end

if Rails.env.development?
  class CouchRest::Connection
    alias_method :old_execute, :execute
    def execute(method, path, options, payload = nil, &block)
      Rails.logger.debug "Couch: #{method} #{Rack::Utils.unescape path} #{options}"
      puts "Couch: #{method} #{Rack::Utils.unescape path} #{options}"
      old_execute(method, path, options, payload, &block)
    end
  end
end
# Bug in actionview error handling, remove for versions > 6.0.2.1
module ActionView
  # = Action View Errors
  class ActionViewError < StandardError #:nodoc:
  end

  class EncodingError < StandardError #:nodoc:
  end

  class WrongEncodingError < EncodingError #:nodoc:
    def initialize(string, encoding)
      @string, @encoding = string, encoding
    end

    def message
      @string.force_encoding(Encoding::ASCII_8BIT)
      "Your template was not saved as valid #{@encoding}. Please " \
      "either specify #{@encoding} as the encoding for your template " \
      "in your text editor, or mark the template with its " \
      "encoding by inserting the following as the first line " \
      "of the template:\n\n# encoding: <name of correct encoding>.\n\n" \
      "The source of your template was:\n\n#{@string}"
    end
  end

  class MissingTemplate < ActionViewError #:nodoc:
    attr_reader :path

    def initialize(paths, path, prefixes, partial, details, *)
      @path = path
      prefixes = Array(prefixes)
      template_type = if partial
        "partial"
      elsif /layouts/i.match?(path)
        "layout"
      else
        "template"
      end

      if partial && path.present?
        path = path.sub(%r{([^/]+)$}, "_\\1")
      end
      searched_paths = prefixes.map { |prefix| [prefix, path].join("/") }

      out  = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n"
      out += paths.compact.map { |p| "  * #{p.to_s.inspect}\n" }.join
      super out
    end
  end

  class Template
    # The Template::Error exception is raised when the compilation or rendering of the template
    # fails. This exception then gathers a bunch of intimate details and uses it to report a
    # precise exception message.
    class Error < ActionViewError #:nodoc:
      SOURCE_CODE_RADIUS = 3

      # Override to prevent #cause resetting during re-raise.
      attr_reader :cause

      def initialize(template)
        super($!.message)
        set_backtrace($!.backtrace)
        @cause = $!
        @template, @sub_templates = template, nil
      end

      def file_name
        @template.identifier
      end

      def sub_template_message
        if @sub_templates
          "Trace of template inclusion: " +
          @sub_templates.collect(&:inspect).join(", ")
        else
          ""
        end
      end

      def source_extract(indentation = 0)
        return [] unless num = line_number
        num = num.to_i

        source_code = @template.source.split("\n")

        start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
        end_on_line   = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min

        indent = end_on_line.to_s.size + indentation
        return [] unless source_code = source_code[start_on_line..end_on_line]

        formatted_code_for(source_code, start_on_line, indent)
      end

      def sub_template_of(template_path)
        @sub_templates ||= []
        @sub_templates << template_path
      end

      def line_number
        @line_number ||=
          if file_name
            regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
            $1 if message =~ regexp || backtrace.find { |line| line =~ regexp }
          end
      end

      def annotated_source_code
        source_extract(4)
      end

      private
        def source_location
          if line_number
            "on line ##{line_number} of "
          else
            "in "
          end + file_name
        end

        def formatted_code_for(source_code, line_counter, indent)
          indent_template = "%#{indent}s: %s"
          source_code.map do |line|
            line_counter += 1
            indent_template % [line_counter, line]
          end
        end
    end
  end

  TemplateError = Template::Error

  class SyntaxErrorInTemplate < TemplateError #:nodoc
    def initialize(template, offending_code_string)
      @offending_code_string = offending_code_string
      super(template)
    end

    def message
      <<~MESSAGE
        Encountered a syntax error while rendering template: check #{@offending_code_string}
      MESSAGE
    end

    def annotated_source_code
      @offending_code_string.split("\n").map.with_index(1) { |line, index|
        indentation = " " * 4
        "#{index}:#{indentation}#{line}"
      }
    end
  end
end

require 'simply_stored'
module SimplyStored
  module Couch
    def freeze
      self
    end

    module ClassMethods
      def after_commit(*)
        # Paperclip has ActiveRecord lock, do not use this
      end
    end
  end
end

# Ugly fix for the updated json gem changes
#module JSON
  #class << self
    #alias :old_parse :parse
    #def parse(json, args = {})
      #args[:create_additions] = true
      #old_parse(json, args)
    #end
  #end
#end
#MultiJson.engine = :json_gem

# This is a fix for testing models that
# are frozen after destroy and then extended
# by active_decorator when running the specs
module Mozo
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)
    config.autoload_paths << Rails.root.join('app/services').to_s

    # Only load the plugins named here, in the order given (default is alphabetical).
    # :all can be used as a placeholder for all plugins not explicitly named.
    # config.plugins = [ :exception_notification, :ssl_requirement, :all ]

    # Activate observers that should always be running.
    # config.active_record.observers = :cacher, :garbage_collector, :forum_observer

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'
    #config.time_zone = 'UTC'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    config.i18n.default_locale = :en
    config.i18n.available_locales = [:en, :nl]

    # Configure the default encoding used in templates for Ruby 1.9.
    config.encoding = "utf-8"

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += [:password, :image] # image will be base64 string from ember (supplier/product)

    # Enable escaping HTML in JSON.
    config.active_support.escape_html_entities_in_json = true

    # initializer 'mozo.cmtool', after: 'cmtool.build_menu' do
    config.after_initialize do
      Cmtool::Menu.register do
        before :users do
          group label: :mozo do # Allow other tools to inject into the mozo menu
            title 'Mozo'
            resource_link UserFeedback, scope: :admin
            resource_link User, scope: :admin
            resource_link Supplier, scope: :admin
            resource_link Section, scope: :admin
            resource_link Table, scope: :admin
            resource_link SvgElement, scope: :admin
            engine_link Rails.application, title: 'Go to the website', path: '/'
          end
        end
      end
    end


    #config.handlebars.templates_root = %w[supplier/app/templates waiter/app/templates user/app/templates] if defined?(Ember::Rails) && defined?(Handlebars)

    config.generators do |g|
      g.orm :simply_stored
      g.template_engine :slim
      g.test_framework :rspec
    end

    # Use SQL instead of Active Record's schema dumper when creating the database.
    # This is necessary if your schema can't be completely dumped by the schema dumper,
    # like if you have constraints or database-specific column types
    # config.active_record.schema_format = :sql

    config.action_view.field_error_proc = Proc.new do |html_tag, instance|
      "#{html_tag}".html_safe
    end

    # Enforce whitelist mode for mass assignment.
    # This will create an empty whitelist of attributes available for mass-assignment for all models
    # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
    # parameters by using an attr_accessible or attr_protected declaration.
    # config.active_record.whitelist_attributes = true

    # Enable the asset pipeline
    config.assets.enabled = true
    #config.assets.precompile += ['supplier/application.css', 'user/application.css', 'qr_sheet/application.css', 'waiter/application.css']
    config.default_url_options = {format: 'html'}

    config.to_prepare do
      Devise::Mailer.layout "mail"
      Devise::Mailer.class_eval do
        helper :mail
      end
    end

    # Version of your assets, change this if you want to expire all your assets
    config.assets.version = '1.0'
  end
end
require 'mozo'
require 'rqrcode-rails3'
