<?php

namespace App\Paper;

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

class CinemaHelios implements Cinema
{

    private $cinemaId;
    private $day;

    private $cinemas = [2 => 'Helios Alfa', 49 => 'Helios Metropolia'];

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

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

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

        if (!is_array($this->cinemaId)) {
            $this->cinemaId = (array)$this->cinemaId;
        }

        $documents = [];
        foreach ($this->cinemaId as $cinema) {
            $url = 'http://www.helios.pl/2,Gdansk/Repertuar/axRepertoire/?dzien=' . $this->day . '&kino=' . $cinema;
            $data = json_decode(file_get_contents($url));

            $document = new Document();
            $data->html = str_replace(["\n", "\t"], '', $data->html);
            $document->loadHtml($data->html);
            $documents[] = $document;
        }
        return $documents;
    }

    function parseRepertoire()
    {
        $documents = $this->fetchRepertorire();
        $cinemas = [];
        foreach ($documents as $document) {
            $movies = [];
            foreach ($document->find('.seance') as $seans) {
                $movie = [];
                $movie['title'] = trim($seans->find('.movie-title')[0]->text());

                $hours = [];
                foreach ($seans->find('.time li') as $hour) {
                    $hours[] = $hour->text();
                }
                $movie['hours'] = array_unique($hours);
                $movies[] = $movie;
            }
            $cinemas[] = $movies;
        }
        return $cinemas;
    }

    function convertToPrint()
    {
        $cinemas = $this->parseRepertoire();
        $text = '';
        foreach ($cinemas as $cinemaId => $filmy) {
            $text .= "Repertuar " . $this->cinemas[$this->cinemaId[$cinemaId]] . "\n";
            $text .= date_create()->modify("+$this->day day")->format('d-m-Y') . "\n\n";

            foreach ($filmy as $film) {
                $text .= $film['title'] . "\n";
                $text .= implode(', ', array_unique($film['hours'])) . "\n\n";
            }
            $text .= "\n";
        }
        return $text;
    }
}