# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module CustomCss
      SETTING_NAME = 'plugin_redmine_custom_css'
      DEFAULTS = {'css' => '', 'javascript' => ''}.freeze
      CSS_CONFIG = Sanitize::Config.merge(
        Sanitize::Config::RELAXED,
        css: {protocols: Sanitize::Config::RELAXED[:css][:protocols] + ['data']}
      ).freeze

      module_function

      def css
        settings.fetch('css', '').to_s
      end

      def javascript
        settings.fetch('javascript', '').to_s
      end

      def sanitized_css
        return '' if css.blank?

        Sanitize::CSS.stylesheet(css, CSS_CONFIG)
      end

      def update(css:, javascript:)
        ensure_setting_defined
        Setting.send("#{SETTING_NAME}=", settings.merge('css' => css.to_s, 'javascript' => javascript.to_s))
      end

      def legacy_renderer_active?
        defined?(RedmineCustomCss::HookListener)
      end

      def settings
        ensure_setting_defined
        DEFAULTS.merge((Setting.send(SETTING_NAME) || {}).to_h)
      end

      def ensure_setting_defined
        return if Setting.available_settings.key?(SETTING_NAME)

        Setting.define_setting(SETTING_NAME, 'default' => DEFAULTS.dup, 'serialized' => true)
      end
    end
  end
end
