<?php

namespace WoWPress\Api;

class BattleNet extends Api{


    protected $api_url = "https://eu.api.blizzard.com";


    public function getCharacter($name,$realm,int $timeout=360){
        $name = urlencode(strtolower($name));
        $realm = urlencode(strtolower($realm));

        $data = $this->get("/profile/wow/character/$realm/$name", [
            'namespace' => 'profile-eu',
            'locale' => 'en_US',
            'access_token' => $this->bearer()
        ], false, $timeout);

        return $data;
    }

    public function getGuildRank($name,$realm){
        $char = $this->getCharacter($name,$realm);
        $guild = $char['guild']['key']['href'];
        $rank = 99;

        if($char['guild']['name'] != "Nebelkrieger" || $char['guild']['realm']['name'] != "Alexstrasza"){
            $guild = $char['guild']['name'];
            $rank = 99;
            return compact('guild','rank');
        }

        $data = $this->get($guild, [
            'namespace' => 'profile-eu',
            'locale' => 'en_US',
            'access_token' => $this->bearer()
        ], false, -1);
        $data = $this->get($data['roster']['href'], [
            'namespace' => 'profile-eu',
            'locale' => 'en_US',
            'access_token' => $this->bearer()
        ], false, -1);
        foreach($data['members'] as $member){
            if($member['character']['name'] == $name && $member['character']['realm']['slug'] == $char['realm']['slug']){
                $guild = $char['guild']['name'];
                $rank = intval($member['rank']);
                return compact('guild','rank');
            }
        }

        $guild = "-";

        return compact('guild','rank');
    }


    public function getMedia($name,$realm,int $timeout=360){
        $name = urlencode(strtolower($name));
        $realm = urlencode(strtolower($realm));
        $data = $this->get("/profile/wow/character/$realm/$name/character-media", [
            'namespace' => 'profile-eu',
            'locale' => 'en_US',
            'access_token' => $this->bearer()
        ], false, $timeout);

        if(!empty($data['code']) && $data['code'] == 403){
       #    var_dump($data);
       #    exit;
       return false;
        }


        return $data;
    }

}