class OrbitBackendController < ApplicationController
  #before_filter :setup_vars
  #before_filter :set_current_user

 # before_filter {|c| c.front_end_available(@app_title)}
  # before_filter :check_user_can_use
  include OrbitCoreLib::PermissionUnility
  include AdminHelper
  include ApplicationHelper
  
  layout 'new_admin'
  
  def setup_vars
    @app_title = controller_path.split('/')[1].singularize
    @module_app ||= ModuleApp.first(conditions: {:key => @app_title} )
  end

  private

  def force_order_for_visitor
    setup_vars
    set_current_user
  end


  def force_order_for_user
    setup_vars
    set_current_user    
    authenticate_user!
    check_user_can_use
  end

  def check_user_can_use 
    unless check_permission
      #redirect_to polymorphic_path(['panel',@app_title,'back_end','public'])
      redirect_to root_url
    end
  end

  def get_sorted_and_filtered(object_class, query=nil)
    objects = get_objects(object_class, query)
    object_class = object_class.classify.constantize
    if !params[:sort].blank?
      options = params[:sort_options]
      options = [options] if !options.class.eql?(Array)
      options.each do |option|
        if object_class.fields.include?(option)
          if object_class.fields[option].type.to_s.eql?('Object') && !object_class.relations[option].nil?
            objects = get_objects_from_referenced_objects(object_class.fields[option].options[:class_name].constantize, objects, option)
          else
            (objects = objects.order_by(option, params[:direction])) rescue nil
          end
        elsif object_class.relations.include?(option)
          case object_class.relations[option].macro
            when :references_one
              a = Array.new 
              objects.each { |object| a << [get_string_value_from_object(object), object] }
              sorted = params[:direction].eql?('asc') ? a.sort : a.sort.reverse!
              objects = sorted.collect {|x| x[1] }
            when :references_many, :references_and_referenced_in_many
              objects = get_objects_from_self(object_class, objects, option) 
            when :referenced_in
              objects = get_objects_from_referenced_objects(object_class.relations[option].class_name.constantize, objects, "#{option}_id")
          end
        end 
      end
    end
    if @filter
      @filter.each do |key, value|
        case key
          when 'status'
            a = Array.new
            objects.each do |object|
              value.each do |v|
                a << object if object[v]
              end
            end
            objects = a.uniq
          when 'categories'
            a = Array.new
            objects.each do |object|
              a << object if (value.include?(object.send("#{object.class.to_s.underscore}_category").id.to_s) rescue nil)
            end
            objects = a.uniq
          when 'tags'
            a = Array.new
            objects.each do |object|
              object.tags.each do |tag|
                a << object if value.include?(tag.id.to_s)
              end
            end
            objects = a.uniq
          end if value.size > 0
      end
    end
    Kaminari.paginate_array(filter_authorized_objects(objects)).page(params[:page]).per(10)
  end

  def get_string_value_from_object(object)
    s = object.name_translations[I18n.locale.to_s] unless s rescue nil
    s = object.title_translations[I18n.locale.to_s] unless s rescue nil
    s = object.name unless s rescue nil
    s = object.title unless s rescue nil
    s.downcase rescue ''
  end

  def get_objects_from_referenced_objects(object_class, objects, option)    
    referer_ids = objects.distinct(option)
    referenced_objects = object_class.find(referer_ids) rescue nil
    if referenced_objects
      a = Array.new 
      referenced_objects.to_a.each { |referer| a << [get_string_value_from_object(referer), referer.id] }
      sorted = params[:direction].eql?('asc') ? a.sort : a.sort.reverse!
      sorted_objects = sorted.collect {|x| objects.where(option => x[1]).entries }
      sorted_objects.flatten!
      sorted_objects.uniq!
      get_with_nil(objects, option, sorted_objects)
    else
      objects
    end 
  end

  def get_objects_from_self(object_class, objects, option) 
    referenced_class = object_class.relations[option].class_name.constantize
    referenced_objects = referenced_class.all rescue nil
    if referenced_objects
      reverse_relation = nil
      referenced_class.relations.each { |relation| reverse_relation = relation[1].name.to_s if relation[1].class_name.eql?(object_class.to_s) }
      a = Array.new 
      referenced_objects.each { |referenced_object| a << [get_string_value_from_object(referenced_object), referenced_object] }
      a.compact!
      sorted = params[:direction].eql?('asc') ? a.sort : a.sort.reverse!
      sorted_objects = Array.new
      sorted.each {|x| sorted_objects << x[1].send(reverse_relation) }
      sorted_objects.flatten!
      sorted_objects.uniq!
      get_with_nil(objects, option, sorted_objects)
    else
      objects
    end 
  end

  def get_with_nil(objects, option, sorted_objects)
    tmp = Array.new 
    objects.each { |object| tmp << [get_string_value_from_object(object), object] if (object.send(option).blank? || (object.send(option).size == 0 rescue nil)) }
    sorted = params[:direction].eql?('asc') ? tmp.sort : tmp.sort.reverse!
    sorted_tmp = sorted.collect {|a| a[1] }
    a = params[:direction].eql?('asc') ? (sorted_tmp + sorted_objects) : (sorted_objects + sorted_tmp)
    a.flatten
  end


  def get_viewable(object_class, query=nil)
    objects = get_objects(object_class,query).order_by(:created_at, :desc)
    Kaminari.paginate_array(objects).page(params[:page]).per(10)
  end

  def get_objects(object_class, query=nil)
    object_class = object_class.classify.constantize
    # debugger
    # a=1
    if query
      objects = object_class.where(query)
    else
      objects = object_class.all
    end
    objects
  end

  def filter_authorized_objects(objects)
    if(!is_admin? || !is_manager?)
      objects.delete_if{ |object|
        if object.is_pending == true
          if check_permission(:manager)
            object.create_user_id != current_user.id
          else
            !object.send("#{object.class.to_s.underscore}_category").authed_users('fact_check').include?(current_user) rescue false
          end
        else
          false
        end 
      }
    end
    objects
  end
  
end