module OrbitModel

  module Approval

    def self.included(base)
      base.extend ClassMethods
      base.class_eval do
        field :is_checked, :type => Boolean, :default => false
        field :is_pending, :type => Boolean, :default => true 
        field :is_rejected, :type => Boolean, :default => false 
        field :not_checked_reason
        query = {type: 'where', conditions: {is_checked: true, is_rejected: false, is_pending: false}}
        if class_variable_defined?(:@@can_display)
          class_variable_set(:@@can_display, (class_variable_get(:@@can_display) << query))
        else
          class_variable_set(:@@can_display, [query])
        end
        send :include, InstanceMethods
      end
    end

    module InstanceMethods

      def de_pending
        self.is_pending = false
      end

      def de_pending!
        de_pending
        self.save!
      end

      def is_checked?
        !self.is_pending && self.is_checked && (self.is_rejected == false)
      end
      
      def is_pending?
        self.is_pending
      end
      
      def is_rejected?
        !self.is_pending && self.is_rejected && (self.is_rejected == true)
      end
      
      def proc_check(check,not_pass_info = "")
        self.is_checked = true
        if check == "true"
          self.is_rejected = false
        elsif check == "false"
          self.is_rejected = true
          self.not_checked_reason = not_pass_info
        end
      end

    end

    module ClassMethods

      define_method(:can_display) do
        final_query = class_variable_get(:@@can_display).inject('') do |result, query_hash|
          result << "." if result.present?
          result << "#{query_hash[:type]}(#{query_hash[:conditions]})"
          result
        end
        eval(final_query)
      end unless method_defined? :can_display
      
    end
    
  end

end
