class EasyPageTabsController < ApplicationController
  include EasyConcerns::EasyPageTabs

  before_action :find_page

  def load_settings
    @modules = @page.user_tab_modules(@tab, @user, @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 = EasyPageUserTab.add(@page, @user, @entity_id)
    end

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

    redirect_to :back
  end

  def get_content
    @layout_style = @page.layout_path
    render_action_as_easy_tab_content(@tab, @page, @user, @entity_id)
  end

  private

    def find_page
      if params[:id].present?
        @tab = EasyPageUserTab.preload(:page_definition, :user).find(params[:id])
        @page = @tab.page_definition
        @user = @tab.user
        @entity_id = @tab.entity_id
      elsif params[:page_id].present?
        @tab = nil
        @page = EasyPage.find(params[:page_id])
        @user = User.find_by(id: params[:user_id])
        @entity_id = params[:entity_id]
      end

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

end
