class EasyPageTemplateTabsController < ApplicationController
  include EasyConcerns::EasyPageTabs

  before_action :find_template

  def load_settings
    @modules = @template.template_tab_modules(@tab, @entity_id, without_zones: true)
    @modules.keep_if {|mod| mod.module_definition.query_module? }

    @filters = Array(@tab && @tab.settings['filters'])
    @modules_filters_options = modules_filters_options(@modules)

    respond_to do |format|
      format.js
    end
  end

  def save_settings
    if @tab.nil?
      @tab = EasyPageTemplateTab.add(@template, @entity_id)
    end

    @tab.settings[:filters] = parse_filters_settings_from_params
    @tab.save

    redirect_to :back
  end

  private

    # entity_id should always be nil but just in case :-)
    def find_template
      if params[:id].present?
        @tab = EasyPageTemplateTab.preload(:page_template_definition).find(params[:id])
        @template = @tab.page_template_definition
        @entity_id = nil
      elsif params[:template_id].present?
        @tab = nil
        @template = EasyPageTemplate.find(params[:template_id])
        @entity_id = nil
      end

      return render_404 if @template.nil?
    rescue ActiveRecord::RecordNotFound
      render_404
    end

end
