class User < ApplicationRecord
  # after_initialize { |obj| obj.send("#{:full_name}=", obj.send(:full_name).titleize) }
  before_save SafeUrl.new
  devise :database_authenticatable, :registerable, :recoverable, :api, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook] #:confirmable, 
  
  # relations
  has_one :medical_history, dependent: :destroy
  belongs_to :coach, optional: true, class_name: "User"
  belongs_to :reference, optional: true, class_name: "User"
  has_many :tickets, dependent: :delete_all
  # has many relations
  [:cycles, :appointments, :messages, :plans, :cards, :photos].each do |rel|
    has_many rel, dependent: :destroy
    accepts_nested_attributes_for rel, :allow_destroy => true
  end
  
  # UPLOADERS
  [:avatar, :front, :side, :back].each { |_attr| mount_uploader _attr, PhotoUploader }

  # validations
  validates :full_name, presence: true
  validates :email, presence: true, uniqueness: true

  # for trainers
  has_many :trainers, -> { distinct }, through: :plans, foreign_key: "trainer_id"

  # scopes
  scope :admin, -> { where(role: ['admin']) }
  scope :nutritionists, -> { where(role: ['nutritionist','admin']) }
  scope :trainers, -> { where(role: ['trainer','admin','nutritionist']) }
  scope :presencial, -> { where(presencial: true) }
  scope :online, -> { where(presencial: false) }

  # searching
  include PgSearch::Model
  pg_search_scope :search, against: [:email, :full_name, :tel], using: {
    tsearch: { prefix: true }
  }, ignoring: :accents

  # pagination
  self.per_page = 30

  def short_name
    return self.full_name.downcase.gsub("lic. ","").split(" ")[0..1].join(" ").titleize
  end

  def objetivo
    if !self.objective.blank?
      idx = ["lose_weight","mass_increase","competition","maintenance"].index(self.objective)
      return idx ? ["Pérdida de grasa", "Bulking", "Competencia", "Mantenimiento"][idx] : ""
    end
    return "No definido"
  end

  def profile_completed?
    return self.sex.present? && self.height.present? && self.kg.present?
  end

  def get_tmb
		if self.tmb.blank?
      plan = self.plans.order(finish: :asc).last
      if plan.nil?
        return self.tmb
      else
			  return plan.get_tmb
      end
		else
			return self.tmb
		end
	end
  
  def get_mlag
		if self.mlag.blank?
      plan = self.plans.order(finish: :asc).last
      return plan.mlag if !plan.nil?
		end
    return self.mlag
	end

  def admin?
    role == "admin"
  end

  def trainer?
    role == "admin" || role == "trainer"
  end

  def birthday_day
		year = Date.today.year
		mmdd = dob.strftime('%m%d')
		mmdd = '0301' if mmdd == '0229' && !Date.parse("#{year}0101").leap?
		return Date.parse("#{year}#{mmdd}")
	end

  def birth_month
		return dob.strftime('%m')
	end
  
  def birth_day
		return dob.strftime('%d')
	end

  def sexo
    case self.sex
    when "male"
      return "Masculino"
    when "female"
      return "Femenino"
    else
      return "-"
    end
  end

  def weight
    if plans.count > 0
      plan_kg = plans.order(created_at: :asc).last.kg
      _kg = (plan_kg.to_i == 0) ? kg : plan_kg
      return _kg
    else
      return kg
    end
  end

  def default_card
    return self.cards.where(predetermined: true).first
  end

  def age
    return years == 0 ? "edad no definida" : "#{years} años"
  end

  def years
    _years = 0
    _years = Time.zone.now.to_date.year - self.dob.to_date.year if !self.dob.blank?
    return _years
  end

  def random_pass
    food = "manzana_pera_queso_ciruela_mango_mandarina_durazno_manzana_uva_almendra_nuez".split("_")
    sports = "pesas_press_abdomen_espalda_sixpack_fitmom_fitness_olympia_mancuerna_barra_fuerza_hombro_brazo".split("_")
    pass = [sports[rand(0..sports.count-1)],food[rand(0..food.count-1)].capitalize, rand(0..999)].join("")
    self.password_confirmation = self.password = pass
    return pass
  end

  def active?
    plan_active
  end

  def plan_active
    self.plans.where("finish >= ? ", Time.zone.now.to_date - 1.week).order(created_at: :desc).first
  end

  private

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  def self.from_omniauth(auth)
    email = auth["info"].email || "#{auth.uid}@ntsclinic.com"
    where("email= ? or uid= ?", email, auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.presencial = false
      user.email = "#{auth.uid}@ntsclinic.com" if user.email.blank?
      if user.new_record?
        user.password = Devise.friendly_token[0,20]
        user.full_name = "#{auth["info"].first_name} #{auth["info"].last_name}"
        user.remote_avatar_url = auth["info"].image.gsub('http:','https:')
      end
      self.safe_url = SecureRandom.urlsafe_base64(12, false) if self.safe_url.blank?   
      user.save!
    end
  end

end