<?php

namespace WoWPress\Models;

use Wenprise\ORM\WP\User as WPUser;

class User extends WPUser
{

    public static function logged_in(): User{
        if(is_user_logged_in()){
            return User::find(get_current_user_id());
        }
        return false;
    }


    public function characters()
    {
        return $this->hasMany(Character::class)->orderBy('rank');
    }

    public function raiders()
    {
        return $this->hasMany(Character::class, 'user_id')->where('raidchar', true)->orderBy('rank');
    }

    public static function getAvatar($avatar, $user_object)
    {
        if(is_numeric($user_object)){
            $user = User::find($user_object);
            if(!empty($user->ID)){
                return $user->getAvatarAttribute();
            } 
        }
        if(!empty($user_object->user_id)){
            $user = User::find($user_object->user_id);
            if(!empty($user->ID)){
                return $user->getAvatarAttribute();
            }
        }

        return $avatar;
    }

    public function getAvatarAttribute(){
        $chars = $this->characters;
        if (!empty($chars->first())) {
            return $chars->first()->avatar;
        }
        return $this->avatar_url;
    }

    public static function getUsername($username, $user_object)
    {
        
        if(is_numeric($user_object)){
            $user = User::find($user_object);
            if(!empty($user->ID)){
                return $user->getUsernameAttribute();
            } 
        }
        if (!empty($user_object->user_id)) {
            $user = User::find($user_object->user_id);
            return $user->getUsernameAttribute();
        }
        if (!empty($user_object->ID)) {
            $user = User::find($user_object->ID);
            return $user->getUsernameAttribute();
        }

        return $username;
    }

    public function getUsernameAttribute()
    {
        $chars = $this->characters;
        if (!empty($chars->first())) {
            return $chars->first()->name;
        }
        return $this->user_nickname ?: $this->login;
    }

    public function getColorAttribute()
    {
        $chars = $this->characters;
        if (!empty($chars->first())) {
            return $chars->first()->color;
        }
        return "priest";
    }

    public function can($capability){
        return user_can($this->ID,$capability);
    }
}
