# == Schema Information
#
# Table name: commands
#
#  id         :integer          not null, primary key
#  aps        :text
#  commands   :string(255)
#  created_at :datetime
#  updated_at :datetime
#  status     :string(255)
#  result     :text
#

class Command < ActiveRecord::Base
  resourcify
  include AssociatedResource
  include RedisWrapper
  include PublicActivity::Model

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
  { :attributes => proc {|controller, model_instance| {"command(#{model_instance.commands})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.organisation_id },:location_network_id => nil

  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}

  REBOOT = "/sbin/reboot"
  has_and_belongs_to_many :router_inventories
  belongs_to :organisation

  scope :pending, -> { where(status: "pending") }
  scope :not_pending, -> { where('status in (?)', ["success", "waiting for response"]) }

  def set_redis(ri)
    cmds = [];
    (ri.reload.commands.pending || []).each do |x|
      cmds << { "CMD_ID" => x.id,"CMD" => x.commands}
    end
    p "CMD_REDIS: ","CMD_#{ri.mac_id}"
    logger.debug("CMD_REDIS: CMD_#{ri.mac_id} : #{cmds}")
    unless cmds.blank?
      redis_set "CMD_#{ri.mac_id}", cmds.to_json
    else
      redis_del "CMD_#{ri.mac_id}"
    end
  end

  def self.init_cmd(ri,command)
    $redis.set "CMD_INIT_#{ri.mac_id}", command
  end

  def waiting?
    self.status.eql? "waiting for response"
  end

  def pending?
    self.status.eql? "pending"
  end

  def success?
    self.status.eql? "success"
  end
end
