module Pinned
  def cache_key
    @cache_key ||= "" << id << ':pin'
  end

  def pin
    $redis.set cache_key, '1'
    push_pin
  rescue
    nil
  end

  def unpin
    $redis.set cache_key, '0'
    pop_pin
  rescue
    nil
  end

  def pinned?
    $redis.get(cache_key) == '1'
  rescue
    false
  end

  def toggle_pin
    pinned? ? unpin : pin
  rescue
    nil
  end

  def Node.pinned_nodes
    Node.find Node.pinned_node_ids
  rescue
    []
  end

  def push_pin
    pinned = (Node.pinned_node_ids + [id]).uniq
    $redis.set pinned_list_key, pinned.to_json
  rescue
    nil
  end

  def pop_pin
    pinned = Node.pinned_node_ids - [id]
    $redis.set pinned_list_key, pinned.to_json
  rescue
    nil
  end

  def pinned_list_key
    'pinned.nodes'
  end

  def Node.pinned_node_ids
    return [] unless (cached_pins = $redis.get('pinned.nodes')).present?
    JSON.parse cached_pins
  rescue
    []
  end
end
