<?php

namespace App\Fetching;

use App\Fetching\RssFeed;
use App\Utils\Debug;

class NanoGal {
    private $bookmarkList = [];
    private string $nanogalUrl;
    private $nanogalFeed;
    public $nanogalFeedUpdate;
    private $numberEntry;

    /**
     * Constructor for initializing the feed and configuration
     *
     * @param array $params Configuration parameters
     * @return self
     */
    function __construct(array $params) {
        $feed = new RssFeed();
        $this->nanogalFeed = $feed->load($params['config']['fetching']['NanoGal']);
        $this->nanogalFeedUpdate = $feed->lastUpdate();
        $this->numberEntry = $params['config']['numberOfLastItem'];

        return $this;
    }

    /**
     * Retrieves the latest images from the NanoGal feed
     *
     * @return array Returns an array of bookmarks
     */
    public function getLastBookmark(): array {
        $totalEntry = count($this->nanogalFeed->xml->entry);

        if ($totalEntry <= $this->numberEntry) {
            $needItem = $totalEntry;
        } else {
            $needItem = $this->numberEntry;
        }

        for ($i = 0; $i < $needItem; $i++) {
            $bookmarkList[] = [
                'title' => (string)$this->nanogalFeed->xml->entry[$i]->title[0],
                'content' => (string)$this->nanogalFeed->xml->entry[$i]->content,
            ];
        }
        $this->bookmarkList = $bookmarkList;
        return $bookmarkList;
    }

    /**
     * Generates an HTML list of bookmarks from the bookmark list
     *
     * @return string|null Returns the generated HTML string of bookmarks
     */
    public function makeList(): ?string {
        if (!empty($this->bookmarkList)) {

            $htmlBookmark = '';
            foreach ($this->bookmarkList as $value) {
                $htmlBookmark .='
                <figure>
                  ' . $value['content'] . '
                  <figcaption>' . $value['title'] . '</figcaption>
                </figure>';
            }
            $htmlBookmark .= '
            </ul>';
            return $htmlBookmark;
        }
        return null;
    }
}