module Symphonia
  module RendererHelper

    def render_symphonia_table(*args, &block)
      options = args.extract_options!
      query = args[0]
      entities = args[1] || @entities
      r = QueryRender.new(self, query, options)
      r.summarize = options.delete(:show_summarize_row)
      unless block_given?
        block = proc { |renderer, entity| renderer.default_buttons(entity) }
      end
      render(layout: 'layouts/symphonia/query', locals: { renderer: r, entities: entities, options: options }, &block)
    end

    class QueryRender

      attr_reader :query
      attr_accessor :summarize
      OPTIONS = [:without_pagination, :show_checkboxes, :show_radios, :table_css_classes]
      attr_accessor *OPTIONS

      def initialize(helper, query, options = {})
        @_c = helper
        @query = query
        OPTIONS.each do |key|
          send("#{key}=", options[key])
        end
      end

      def show_summarize?
        !!summarize
      end

      def show_checkboxes?
        !!@show_checkboxes
      end

      def show_radios?
        !!@show_radios
      end

      def show_link(entity)
        @_c.link_to(@_c.icon('info-circle', t(:button_show)), entity)
      end

      def edit_link(entity)
        model = @_c.controller.try(:model) || @_c.controller_name
        @_c.link_to(@_c.icon('edit', t(:button_edit)), @_c.edit_polymorphic_path(entity, back_url: @_c.polymorphic_path(model, page: @_c.params[:page])))
      end

      def delete_link(entity)
        @_c.link_to(@_c.icon('del', t(:button_delete)), entity, method: 'DELETE', data: { remote: true, confirm: t(:text_are_you_sure) })
      end

      def default_buttons(entity)
        edit_link(entity) + delete_link(entity)
      end

      def header_tag(column, options = {})
        return '' unless column.header?

        title = column.title
        return title unless column.sort?

        current_column = query.sort_column || SortableTable::SortColumn.new(nil, nil)
        prefix = options.delete(:prefix)
        is_current_column = column.sort_definition.column == current_column.column
        options_class = options.delete(:class)
        css_class = is_current_column ? "current #{current_column.direction} #{options_class}" : options_class
        direction = is_current_column && current_column.direction == 'asc' ? 'desc' : 'asc'
        sort_params = { "#{prefix}sort" => "#{column.sort_definition.column}:#{direction}",
                        "#{prefix}page" => nil }
        @_c.link_to title, query.to_params.merge(sort_params), options.merge({ class: css_class })
      end

      def css_classes(entity)
        css = []
        css << "status--#{entity.status}" if entity.respond_to?(:status)
        css.join("__") + entity.try(:css_classes).to_s
      end

      private

      def t(*args)
        @_c.t(*args)
      end

    end
  end
end