<?php 

namespace Model;

require_once "NewsImage.php";
require_once "NewsSource.php";

class NewsItem extends Model {
  public $id;
  public $title;
  public $author;
  public $content;
  public $published;
  public $edited; 
  public $keywords;

  public $source;
  public $category;
  public $theme;
  public $region;
  
  public $podcast;
  public $images;
  public $video;

  public $url;

  public function __construct($data, $images = null, $podcast = null) {
    parent::__construct($data);
    parent::ConvertToDateTime($this->published);
    parent::ConvertToDateTime($this->edited);

    if($this->edited && ($this->edited->getTimestamp() - $this->published->getTimestamp() < 1800 /* == 30 minutes */)) {
      // If last edit was within grace period, consider it unedited (note: currently RES always saves edited == published on creation)
      $this->edited = null;
    }
    
    $this->source = null;
    if(isset($data->source))
    {
      if(is_object($data->source))
      {
         $this->source = new \Model\NewsSource($data->source->title, $data->source->url, $data->source->show);
      } else if($data->source) {
         $this->source = new \Model\NewsSource($data->source, $data->source_url, $data->showsource);
      }
    }

    if($podcast) {
        $this->podcast = new \Model\Podcast($podcast);
    } else if(isset($data->podcast) && $data->podcast) { 
        $this->podcast = new \Model\Podcast($data->podcast);
    }

    $this->keywords = null;
    if(isset($data->keywords)) {
      if(is_array($data->keywords) || is_object($data->keywords)) {
        $this->keywords = $data->keywords;
      } else if(trim($data->keywords)) { 
        $this->keywords = explode(' ', $data->keywords);
      }
    }

    if(isset($data->region)) { 
      if(is_object($data->region)) { 
        $this->region = new \Model\NewsRegion($data->region->title, $data->region->slug);
      } else {
        $this->region = new \Model\NewsRegion($data->region, $data->region_slug);
      }
    }

    if(isset($data->theme)) { 
      if(is_object($data->theme)) { 
        $this->theme = new \Model\NewsRegion($data->theme->title, $data->theme->slug);
      } else {
        $this->theme = new \Model\NewsRegion($data->theme, $data->theme_slug);
      }
    }
  

    $images = ($images != null) ? $images
            : (isset($data->images) ? $data->images : null);
    if($images) {
        $this->images = [];
        foreach($images as $image) {
            $this->images[] = new NewsImage($image, '/img/news/');
        }
    }

    $this->url = "/nieuws/{$this->id}/" . parent::url_slug($this->title);
  }

  public function excerpt() {
    $hasImages = count($this->images) > 0;
    $maxLength = $hasImages ? 200 : 500;
    return '<p class="news-excerpt ' . ($hasImages ? 'short' : 'long') . '">' . 
      substr($this->content, 0, $maxLength) . 
      (strlen($this->content) > $maxLength ? '...' : '') . 
      '</p>'; 
  }
}
