module Votable
  extend ActiveSupport::Concern

  included do
    has_many :votes, as: :votable

    def already_upvoted?(ip)
      !votes.where(ip: ip, upvote: 1).empty?
    end

    def already_downvoted?(ip)
      !votes.where(ip: ip, upvote: 0).empty?
    end

    def upvote!(ip)
      return false if already_upvoted?(ip)

      if already_downvoted?(ip)
        votes.where(ip: ip, upvote: 0).first.delete
        self.downvotes -= 1
        save!
      else
        votes.create(ip: ip, upvote: 1).save
        self.upvotes += 1
        save!
      end
    end

    def downvote!(ip)
      return false if already_downvoted?(ip)

      if already_upvoted?(ip)
        votes.where(ip: ip, upvote: 1).first.delete
        self.upvotes -= 1
        save!
      else
        votes.create(ip: ip, upvote: 0).save
        self.downvotes += 1
        save!
      end
    end

    def like!(url, name)
      return false unless votes.where(liker_url: url).empty?

      votes.create(liker_url: url, liker_name: name, upvote: 1).save
      self.upvotes += 1
      save!
    end
  end
end