<commit_before># encoding: utf-8

module Carto
  module NamedMaps
    class Template
      NAMED_MAPS_VERSION = '0.0.1'.freeze
      NAME_PREFIX = 'tpl_'.freeze
      AUTH_TYPE_OPEN = 'open'.freeze
      AUTH_TYPE_SIGNED = 'token'.freeze
      EMPTY_CSS = '#dummy{}'.freeze

      TILER_WIDGET_TYPES = {
        'category': 'aggregation',
        'formula': 'formula',
        'histogram': 'histogram',
        'list': 'list',
        'time-series': 'histogram'
      }.freeze

      DATAVIEW_TEMPLATE_OPTIONS = [:column, :aggregation, :aggregationColumn, :aggregation_column, :operation].freeze

      def initialize(visualization)
        # TODO: Remove when it's safe to assume thais confussion wont' happen.
        raise 'Carto::NamedMaps::Template needs a Carto::Visualization' unless visualization.is_a?(Carto::Visualization)

        @visualization = visualization
      end

      def to_hash
        @template ||= stats_aggregator.timing('named-map.template-data') do
          {
            name: name,
            auth: auth,
            version: NAMED_MAPS_VERSION,
            placeholders: placeholders,
            layergroup: {
              layers: layers,
              stat_tag: @visualization.id,
              dataviews: dataviews,
              analyses: analyses_definitions
            },
            view: view
          }
        end
      end

      def to_json
        to_hash.to_json
      end

      def name
        (NAME_PREFIX + @visualization.id).gsub(/[^a-zA-Z0-9\-\_.]/, '').tr('-', '_')
      end

      private

      def placeholders
        placeholders = {}

        layers = @visualization.map.layers

        last_index, carto_layers_visibility_placeholders = layer_visibility_placeholders(layers.select(&:carto_layer?))
        _, torque_layer_visibility_placeholders = layer_visibility_placeholders(layers.select(&:torque?),
                                                                                starting_index: last_index)

        placeholders = placeholders.merge(carto_layers_visibility_placeholders)
        placeholders = placeholders.merge(torque_layer_visibility_placeholders)

        placeholders
      end

      def layer_visibility_placeholders(layers, starting_index: 0)
        placeholders = {}

        index = starting_index
        layers.each do |layer|
          placeholders["layer#{index}".to_sym] = {
            type: 'number',
            default: layer.options[:visible] ? 1 : 0
          }
          index += 1
        end

        [index, placeholders]
      end

      def layers
        layers = []
        layer_index = -1 # forgive me for I have sinned

        @visualization.map.named_maps_layers.each do |layer|
          if layer.data_layer?
            layer_index += 1

            layers.push(type: 'cartodb', options: options_for_cartodb_layers(layer, layer_index))
          elsif layer.base?
            layer_options = layer.options

            if layer_options['type'] == 'Plain'
              layers.push(type: 'plain', options: options_for_plain_basemap_layers(layer_options))
            else
              layers.push(type: 'http', options: options_for_http_basemap_layers(layer_options))
            end
          end
        end

        @visualization.map.torque_layers.each do |layer|
          layer_index += 1
          layers.push(type: 'torque', options: common_options_for_carto_and_torque_layers(layer, layer_index))
        end

        layers
      end

      def options_for_plain_basemap_layers(layer_options)
        layer_options['image'].empty? ? { color: layer_options['color'] } : { imageUrl: layer_options['image'] }
      end

      def options_for_http_basemap_layers(layer_options)
        options = {}

        options[:urlTemplate] = layer_options['urlTemplate'] if layer_options['urlTemplate'].present?
        options[:subdomains] = layer_options['subdomains'] if layer_options['subdomains']

        options
      end

      def options_for_cartodb_layers(layer, index)
        options = common_options_for_carto_and_torque_layers(layer, index)

        layer_options = layer.options
        layer_options_sql_wrap = layer_options[:sql_wrap]
        layer_options_query_wrapper = layer_options[:query_wrapper]

        options[:sql_wrap] = layer_options_sql_wrap || layer_options_query_wrapper

        options
      end

      def common_options_for_carto_and_torque_layers(layer, index)
        layer_options = layer.options

        options = {
          cartocss: layer_options.fetch('tile_style').strip.empty? ? EMPTY_CSS : layer_options.fetch('tile_style'),
          cartocss_version: layer_options.fetch('style_version')<commit_msg>add check for image presence<commit_after># encoding: utf-8

module Carto
  module NamedMaps
    class Template
      NAMED_MAPS_VERSION = '0.0.1'.freeze
      NAME_PREFIX = 'tpl_'.freeze
      AUTH_TYPE_OPEN = 'open'.freeze
      AUTH_TYPE_SIGNED = 'token'.freeze
      EMPTY_CSS = '#dummy{}'.freeze

      TILER_WIDGET_TYPES = {
        'category': 'aggregation',
        'formula': 'formula',
        'histogram': 'histogram',
        'list': 'list',
        'time-series': 'histogram'
      }.freeze

      DATAVIEW_TEMPLATE_OPTIONS = [:column, :aggregation, :aggregationColumn, :aggregation_column, :operation].freeze

      def initialize(visualization)
        # TODO: Remove when it's safe to assume thais confussion wont' happen.
        raise 'Carto::NamedMaps::Template needs a Carto::Visualization' unless visualization.is_a?(Carto::Visualization)

        @visualization = visualization
      end

      def to_hash
        @template ||= stats_aggregator.timing('named-map.template-data') do
          {
            name: name,
            auth: auth,
            version: NAMED_MAPS_VERSION,
            placeholders: placeholders,
            layergroup: {
              layers: layers,
              stat_tag: @visualization.id,
              dataviews: dataviews,
              analyses: analyses_definitions
            },
            view: view
          }
        end
      end

      def to_json
        to_hash.to_json
      end

      def name
        (NAME_PREFIX + @visualization.id).gsub(/[^a-zA-Z0-9\-\_.]/, '').tr('-', '_')
      end

      private

      def placeholders
        placeholders = {}

        layers = @visualization.map.layers

        last_index, carto_layers_visibility_placeholders = layer_visibility_placeholders(layers.select(&:carto_layer?))
        _, torque_layer_visibility_placeholders = layer_visibility_placeholders(layers.select(&:torque?),
                                                                                starting_index: last_index)

        placeholders = placeholders.merge(carto_layers_visibility_placeholders)
        placeholders = placeholders.merge(torque_layer_visibility_placeholders)

        placeholders
      end

      def layer_visibility_placeholders(layers, starting_index: 0)
        placeholders = {}

        index = starting_index
        layers.each do |layer|
          placeholders["layer#{index}".to_sym] = {
            type: 'number',
            default: layer.options[:visible] ? 1 : 0
          }
          index += 1
        end

        [index, placeholders]
      end

      def layers
        layers = []
        layer_index = -1 # forgive me for I have sinned

        @visualization.map.named_maps_layers.each do |layer|
          if layer.data_layer?
            layer_index += 1

            layers.push(type: 'cartodb', options: options_for_cartodb_layers(layer, layer_index))
          elsif layer.base?
            layer_options = layer.options

            if layer_options['type'] == 'Plain'
              layers.push(type: 'plain', options: options_for_plain_basemap_layers(layer_options))
            else
              layers.push(type: 'http', options: options_for_http_basemap_layers(layer_options))
            end
          end
        end

        @visualization.map.torque_layers.each do |layer|
          layer_index += 1
          layers.push(type: 'torque', options: common_options_for_carto_and_torque_layers(layer, layer_index))
        end

        layers
      end

      def options_for_plain_basemap_layers(layer_options)
        layer_options['image'].present? ? { imageUrl: layer_options['image'] } : { color: layer_options['color'] }
      end

      def options_for_http_basemap_layers(layer_options)
        options = {}

        options[:urlTemplate] = layer_options['urlTemplate'] if layer_options['urlTemplate'].present?
        options[:subdomains] = layer_options['subdomains'] if layer_options['subdomains']

        options
      end

      def options_for_cartodb_layers(layer, index)
        options = common_options_for_carto_and_torque_layers(layer, index)

        layer_options = layer.options
        layer_options_sql_wrap = layer_options[:sql_wrap]
        layer_options_query_wrapper = layer_options[:query_wrapper]

        options[:sql_wrap] = layer_options_sql_wrap || layer_options_query_wrapper

        options
      end

      def common_options_for_carto_and_torque_layers(layer, index)
        layer_options = layer.options

        options = {
          cartocss: layer_options.fetch('tile_style').strip.empty? ? EMPTY_CSS : layer_options.fetch('tile_style'),
          cartocss_version: layer_options.fetch('style_version')
{'fraction_non_alphanumeric': 0.09206450923849194, 'fraction_numerical': 0.002776887749652889, 'mean_word_length': 2.328830430145752, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1663980', 'n_tokens_mistral': 2761, 'n_tokens_neox': 2622, 'n_words': 489}