<?php

namespace CCDN\Helpers\Api\Response\Items;

class SeasonsContainer extends Item implements SeasonsContainerInterface
{

    /**
     * @inheritDoc
     */
    public function getAllEpisodesCount()
    {
        $count = 0;

        if ($this->isEmpty()) {
            return null;
        }

        foreach ($this->data as $seasons) {
            foreach ($seasons['episodes'] as $key => $episode) {
                if (empty($episode['iframe_url'])) {
                    unset($seasons['episodes'][$key]);
                }
            }
            $count += count($seasons['episodes']);
        }

        return $count;
    }

    /**
     * @inheritDoc
     */
    public function getNewEpisodeList()
    {
        $newEpisodeList = [];

        $lastSeason = $this->getLast()->getData();

        foreach ($lastSeason['episodes'] as $episode) {
            if (empty($episode['iframe_url'])) {
                $newEpisodeList[] = new Episode($episode);
            }
        }

        return $newEpisodeList;
    }

    /**
     * @inheritDoc
     */
    public function getLast()
    {
        if ($this->isEmpty()) {
            return new Season();
        }
        $seasonCount = $this->getCount();
        do {
            $season = $this->get($seasonCount);
            $iframe = $season->getEpisodes()->getLast()->getIframeUrl()->get();
            $seasonCount--;
        } while (empty($iframe) && $seasonCount >= 1);

        return $season;
    }

    /**
     * @inheritDoc
     */
    public function get($number)
    {
        if ($this->isEmpty()) {
            return new Season();
        }

        foreach ($this->data as $season) {
            if ($season['season'] === $number) {
                return new Season($season);
            }
        }

        return new Season();
    }

    /**
     * @inheritDoc
     */
    public function getAll()
    {
        $items = [];
        if (!$this->isEmpty()) {
            foreach ($this->data as $episode) {
                $items[] = new Season($episode);
            }
        }
        return $items;
    }
}
