<?php

namespace WoWPress\Models;

use Illuminate\Support\Collection;
use Wenprise\Eloquent\Model;
use WoWPress\Api\BattleNet;
use WoWPress\Api\WoWAudit;

class SKSHistory extends Model
{

    protected $table = "wowpress_sks_history";
    protected $primaryKey = 'ID';
    protected $guarded = ['ID'];



    public function getLatest()
    {
        return self::where('list_name', $this->list_name)->where('active', true)->latest('created_at')->first();
    }

    public static function getLatestList($list_name)
    {
        return static::where('list_name', $list_name)->where('active', true)->latest('created_at')->first();
    }

    private function setList($list_array)
    {
        $this->list_json = json_encode($list_array);
    }


    public static function createList(string $list_name, $list_json)
    {
        $sks = new static();
        $sks->list_name = $list_name;
        if (is_array($list_json)) {
            $list_json = json_encode($list_json);
        }
        $sks->list_json = $list_json;
        $sks->active = true;
        $sks->fixOrder();
        return $sks;
    }

    public function fillWithRaiders()
    {
        $options = get_option('wowpress_api');
        if (isset($options['wowaudit'])) {
            $key = get_option('wowpress_api')['wowaudit']['key'];
        } else {
            return false;
        }
        $api = new WoWAudit(null, $key);
        $roster = $api->getRoster();
        $list = [];
        foreach ($roster as $id => $character) {
            if (!empty($character['name'])) {
                $list[] = [
                    'char' => $character['name'] . "-" . $character['realm'],
                    'rank' => $id + 1,
                    'active' => true,
                ];
            }
        }


        $this->list_json = json_encode($list);
    }

    public function getListArrayAttribute()
    {
        return json_decode($this->list_json, true);
    }

    public function shuffle()
    {
        $ranks = range(1, count($this->list_array));
        shuffle($ranks);
        $list = $this->list_array;
        foreach ($list as $id => &$list_item) {
            $list_item['rank'] = array_pop($ranks);
        }
        $this->saveList($list);
    }

    private function getChar($char)
    {
        foreach ($this->list_array as $list_item) {
            if ($list_item['char'] == $char) {
                return $list_item;
            }
        }
        return false;
    }

    private function sort($list)
    {
        usort($list, fn($a, $b) => $a['rank'] - $b['rank']);
        return $list;
    }


    public function fixOrder()
    {
        $data = $this->list_array;

        // Separate active and inactive items
        $activeItems = [];
        $inactiveItems = [];
        foreach ($data as $item) {
            if ($item["active"]) {
                $activeItems[] = $item;
            } else {
                $inactiveItems[] = $item;
            }
        }

        // Sort the active items by rank
        usort($activeItems, function ($a, $b) {
            return $a["rank"] - $b["rank"];
        });

        // Reassign ranks starting from 1 for active items
        $rankCounter = 0;
        foreach ($activeItems as $key => $item) {
            $rankCounter += 1;
            foreach ($inactiveItems as $inactive_item) {
                if ($inactive_item['rank'] == $rankCounter) {
                    $rankCounter += 1;
                }
            }
            $item["rank"] = $rankCounter;
            $activeItems[$key] = $item;
        }

        // Merge active and inactive items back
        $data = array_merge($inactiveItems, $activeItems);

        $data = $this->sort($data);


        $this->setList($data);
    }

    public function loot($char)
    {
        if ($looter = $this->getChar($char)) {
            if ($looter['active']) {
                $list = $this->list_array;
                foreach ($list as $id => &$list_item) {
                    if ($list_item['rank'] == $looter['rank']) {
                        $list[$id]['rank'] = PHP_INT_MAX; //Ans Ende der Liste mit dem Looter
                        break;
                    }
                }

                return $this->saveList($list);
            }
        }
        return false;
    }

    public function saveList($list_array)
    {
        $this->active = false;
        $this->save();
        $new  = self::createList($this->list_name, $list_array);
        $new->save();
        return $new;
    }

    public function toggleActive($rank)
    {
        $list = $this->list_array;
        foreach ($list as &$list_item) {
            if ($rank == $list_item['rank']) {
                $list_item['active'] = !$list_item['active'];
                return $this->saveList($list);
            }
        }
        return false;
    }

    public function getList()
    {
        return $this->list_array;
    }

    public function getCharData($char)
    {
        list($name, $realm) = explode("-", $char);
        $character  =  Character::whereName($name)->whereRealm($realm)->first();
        if (empty($character)) {
            $character = new Character();
            $character->name = $name;
            $character->realm = $realm;
            $character->class = "priest";
        }

        return $character;
    }

    public function getPreviousList()
    {
        return SKSHistory::where('list_name', $this->list_name)->whereNot('active')->where('created_at', '<', $this->created_at)->orderBy('updated_at','DESC')->first();
    }

    public function getNextList()
    {
        return SKSHistory::where('list_name', $this->list_name)->whereNot('active')->where('created_at', '>', $this->created_at)->orderBy('updated_at','DESC')->first();
    }

    public function undo()
    {
        $lastItem = $this->getPreviousList();
        $lastItem->active = true;
        $lastItem->save();
        $this->active = false;
        $this->save();
    }

    public function redo()
    {
        $nextItem = $this->getNextList();
        $nextItem->active = true;
        $nextItem->save();
        $this->active = false;
        $this->save();
    }

    public function removeChar($char, $realm = "")
    {
        if ($realm) {
            $char = $char . "-" . $realm;
        }
        $list = $this->list_array;
        foreach ($list as $id => $list_item) {
            if (!$list_item['active'] && $list_item['char'] == $char) {
                unset($list[$id]);
            }
        }
        $this->saveList($list);
    }

    public function addChar($char, $realm = "")
    {
        if ($realm) {
            $char = $char . "-" . $realm;
        }
        $list = $this->list_array;
        foreach ($list as $list_item) {
            if ($list_item['char'] == $char) {
                return false;
            }
        }
        $list[] = [
            'rank' => PHP_INT_MAX,
            'active' => true,
            'char' => $char
        ];
        $this->saveList($list);
    }
}