<?php

namespace App\Paper;

use App\Paper\Interfaces\Cinema;
use DiDom\Document;

class CinemaGdynskieCentrumFilmowe implements Cinema
{

    private $cinemaId;
    private $day;

    public function setCinemaId($cinemaId)
    {
        $this->cinemaId = $cinemaId;
    }

    public function setDay($day)
    {
        $this->day = $day;


    }

    function fetchRepertorire()
    {
        if (is_null($this->day))
            throw new \Exception('Day not set.');

//        if (!is_array($this->cinemaId)) {
//            $this->cinemaId = (array)$this->cinemaId;
//        }
        $url = 'http://www.gdynskiecentrumfilmowe.pl/kino_studyjne/repertuar/,' . strtotime($this->day) . ',_' . $this->day . '.html';
        return file_get_contents($url);

    }

    function parseRepertoire()
    {
        $rawPage = $this->fetchRepertorire();

        $document = new Document();
        $document->loadHtml($rawPage);
        $moviesData = [];



        $movies = $document->find('.articles .article-item');
        foreach ($movies as $movie) {

            $movieData = [];
            $movieData['title'] = $movie->first('.item-title-int::text');
            $movieData['hours'] = [];
            foreach ($movie->find('.projection span') as $projection) {
                $movieData['hours'][] = $projection->innerHtml();
            }
//            $text .= implode(', ', array_unique($hours)) . "\n\n";
            $moviesData[] = $movieData;
        }

        return $moviesData;

    }

    function convertToPrint()
    {
        $movies = $this->parseRepertoire();

        $text = '';
        $text .= "Repertuar Gdyńskie Centrum Filmowe\n";
        $text .= str_replace('_', '-', $this->day) . "\n\n";

        foreach ($movies as $movie) {

            $text .= $movie['title']. "\n";
            $text .= implode(', ', array_unique($movie['hours'])). "\n\n";
        }

        return $text;
    }
}