class User < ApplicationRecord
  has_many :screenshots, inverse_of: :user

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,
    # :registerable,
    # :recoverable,
    # :rememberable,
    :trackable,
    # :validatable,
    :timeoutable,
    # :lockable,
    :omniauthable, omniauth_providers: [
      :salsa,
      # :launchpad,
      # :stackexchange,
      # :google_oauth2,
      # :amazon,
      # :github
    ]

  include Gravtastic
  gravtastic size: 120

  # Return a human-friendly string describing the user's SSO provider
  def pretty_provider
    case self.provider
    # when 'launchpad'
    #   'Ubuntu One/Launchpad'
    # when 'stackexchange'
    #   'StackExchange'
    # when 'google_oauth2'
    #   'Google'
    # when 'amazon'
    #   'Amazon'
    # when 'github'
    #   'GitHub'
    when 'salsa'
      'salsa.debian.org'
    else
      'local authentication'
    end
  end

  def pretty_name
    if self.pseudo
      'Anonymous'
    elsif self.name?
      self.name
    else
      'Dr. Who'
    end
  end

  def pretty_role
    if self.pseudo
      'Contributor'
    elsif self.moderator_role
      'Moderator'
    elsif self.admin_role
      'Admin'
    end
  end

  def self.from_omniauth(auth)
    where(provider: auth.provider, email: auth.info.email).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.name = auth.info.name
      # Set a random password
      user.password = Devise.friendly_token[0,20]

      # Users coming through salsa.debian.net/OpenID-Connect will get moderator role
      if user.email.end_with?('@debian.org') && user.provider=='salsa'
        user.moderator_role = true
      end
    end
  end

  # Seamlessly create a user account for the current visitor.
  # It helps track uploads because uploaded screenshots get assigned
  # to this user record.
  # TODO: The user can later decide to use a real account and get their screenshots transferred to that.
  def self.create_pseudo_user
    generated_password = Devise.friendly_token.first(8)
    new_user = User.create(
      name: 'Anonymous',
      password: generated_password,
      pseudo: true
    )
    return new_user
  end

  def to_s
    if self.pseudo
      "Pseudo user #{self.id}"
    else
      "#{self.email} (#{self.provider})"
    end
  end
end
