require 'faraday'
class Url < ActiveRecord::Base
  belongs_to :user

  validates :long_url, presence: true
  validate :real_url?

  before_save :init

  def init
    self.generate_short_url
    self.click_counter = 0 unless persisted?
  end

  def real_url?
    url = self.long_url
    url.prepend('http://') unless url.start_with?('http://')
    begin
      Faraday.head(url).status
    rescue StandardError=>e
      errors.add(:long_url, 'must be valid')
    end
  end

  def generate_short_url
    unless self.short_url
      short_url = Array.new(7){ [*'0'..'9', *'a'..'z', *'A'..'Z'].sample }.join
      unique_short_url?(short_url) ? self.short_url = short_url : generate_short_url
    end
  end

  def unique_short_url?(short_url)
    return true if Url.where(short_url: short_url).empty?
  end

  def increment_counter
    increment! :click_counter
  end
end