<?php

namespace WoWPress\Models;

use MO;
use Wenprise\Eloquent\Model;
use WoWPress\Api\BattleNet;
use WoWPress\Api\WoWAudit;

class Raid extends Model
{

    protected $table = "wowpress_raids";
    public $timestamps = false;
    protected $primaryKey = 'ID';
    protected $guarded = ['ID'];

    public $signups;

    private $api;
    public $notes;

    public $encounters;
    public $partial;

    public function __construct($attrs = [])
    {
        parent::__construct($attrs);
        $options = get_option('wowpress_api');
        if (isset($options['bnet'])) {
            $key = get_option('wowpress_api')['wowaudit']['key'];
        } else {
            return false;
        }

        $this->api = new WoWAudit(null, $key);
    }

    private function sortRoles($a, $b)
    {
        switch ($a->role) {
            case 'Tank':
                $asort = 0;
                break;
            case 'Heal':
                $asort = 1;
                break;
            case 'Ranged':
                $asort = 2;
                break;
            case 'Melee':
                $asort  = 3;
                break;
            default:
                $asort = 4;
                break;
        }
        switch ($b->role) {
            case 'Tank':
                $bsort = 0;
                break;
            case 'Heal':
                $bsort = 1;
                break;
            case 'Ranged':
                $bsort = 2;
                break;
            case 'Melee':
                $bsort  = 3;
                break;
            default:
                $bsort = 4;
                break;
        }
        return $asort - $bsort;
    }

    public function sync($force = false)
    {

        if (!empty($this->id_wowaudit)) {
            $raid = (object)$this->api->getRaid($this->id_wowaudit, $force);
            if (!empty($raid->id)) {
                $this->title = $raid->instance;
                $this->start = $raid->date . " " . $raid->start_time;
                $this->end = $raid->date . " " . $raid->end_time;
                $this->difficulty = $raid->difficulty;
                $this->status = $raid->status;
                $encounters = $raid->encounters;

                $partial = false;
                $signups = [];
                $sup = [];

                foreach ($encounters as $key => &$encounter) {
                    $partial = $encounter['enabled'] || $partial;
                    if (empty($encounter['selections'])) {
                        $encounter['selections'] = [];
                    }
                    $encounters[$key]['selections'] = collect($encounter['selections']);
                }
                

                $this->partial = $partial;
                foreach ($raid->signups as $signup) {
                    $character = Character::whereName($signup['character']['name'])->whereRealm($signup['character']['realm'])->first();
                    if (empty($character)) {
                        $character = new Character();
                        $character->name = $signup['character']['name'];
                        $character->realm = $signup['character']['realm'];
                        $character->updateFromAPI();
                    }
                    if ($character->class != $signup['class']) {
                        if (!empty($character->user)) {
                            $newchar = $character->user->characters()->where('class', $signup['class'])->first();
                            if (!empty($newchar->ID)) {
                                $character = $newchar;
                            }
                        }
                    }
                    $character->id_wowaudit = $signup['character']['id'];
                    $character->save();
                    $sup[$character->id_wowaudit] = $signup['status'];
                    $s = new Signup();
                    $s->character_id = $character->ID;
                    $s->raid_id = $this->ID;
                    if ($this->partial) {
                        foreach ($encounters as $encounter) {
                            if ($signup['selected']) break;
                            if (empty($encounter['selections'])) continue;
                            foreach ($encounter['selections'] as $selection) {
                                if ($selection['character_id'] == $signup['character']['id']) {
                                    $signup['selected'] = $selection['selected'] || $signup['selected'];
                                    if ($signup['selected']) {
                                        break 2;
                                    }
                                }
                            }
                        }
                    }
                    $s->comment = $signup['comment'];
                    $s->status = $signup['selected'] ? "Selected" : $signup['status'];
                    $s->role = $signup['status'] == "Unknown" ? "Unknown" : $signup['role'];
                    $signups[] = $s;
                }
                
                $this->signups = collect($signups);

                
                foreach ($encounters as &$encounter) {
                    foreach ($encounter['selections'] as $key => &$selection) {
                        $character = Character::where('id_wowaudit', $selection['character_id'])->first();
                        $selection['status'] = $sup[$character->id_wowaudit];

                        $s = new Signup();
                        $s->character_id = $character->ID;
                        $s->raid_id = $this->ID;
                        $s->boss_id = $encounter['id'];
                        $s->status = $selection['selected'] ? "Selected" : $selection['status'];
                        $s->role = $selection['role'];

                        $encounter['selections'][$key] = $s;
                    }
                }
              
               
              

                array_unshift($encounters, [
                    'name' => "Alle Bosse",
                    'id' => 0,
                    'enabled' => true,
                    'notes' => $raid->notes,
                    'selections' => $this->signups,
                ]);

                foreach ($encounters as &$encounter) {
                    $encounter['selections'] = collect($encounter['selections'])->sortBy([fn ($a, $b) => $this->sortRoles($a, $b), 'character_id']);
                }

                $this->encounters = collect($encounters);
            }else{
                return false;
            }
        }

    
        return $this;
    }

    public function getColorAttribute($type = "")
    {
        switch ($this->difficulty) {
            case 'Normal':
                return "shaman";
            case 'Heroic':
                return "warlock";
            case 'Mythic':
                return "deathknight";
            case 'Teamspeak':
                return "hunter";
            default:
                return "priest";
        }
    }

    public function getLinkAttribute()
    {
        return "/raid/" . $this->ID;
    }


    public function getPreviousAttribute()
    {

        $previous = Raid::where('start','<',$this->start)->orderBy('start','DESC')->first();
        return $previous;
    }

    public function getThumbnailAttribute(){

        $clean_name = str_replace([" ","'"],"-",$this->title);
        $clean_name = preg_replace('/[^a-zA-Z0-9_-]/', '', $clean_name);
        $clean_name = strtolower($clean_name);

        return "https://data.wowaudit.com/img/$clean_name-small.jpeg";

    }


    public function getNextAttribute()
    {
        $next = Raid::where('start','>',$this->start)->orderBy('start','ASC')->first();
        return $next;
    }

    public function showSignup($character, $showRole = false, $showStatus = false, $vertical = false)
    {
        $u = $character->user;
        if (!empty($u->ID)) {
            $chars = $u->characters;
        } else {
            $chars = [$character];
        }
        if(!empty($this->id_wowaudit)) $this->sync();
        if (!empty($character->ID) && !empty($this->signups)) {
            foreach ($this->signups as $signup) {
                foreach ($chars as $character) {
                    if ($signup->character->ID == $character->ID) {
                        return $signup->showForm($showRole, $showStatus, $vertical);
                    }
                }
            }
        }

        $s = new Signup();
        $s->raid_id = $this->ID;
        $s->character_id = $character->ID;
        return $s->showForm($showRole,$showStatus,$vertical);

    }
}
