<?php namespace JasonWilliams\Feed\Components;

use Cms\Classes\ComponentBase;
use JasonWilliams\Feed\Models\FeedItem;

class LazyLoadShortFeed extends ComponentBase
{
    public function componentDetails()
    {
        return [
            'name'        => 'Short Feed (Lazy Load)',
            'description' => 'Displays a mini-feed of the most recent feed items, retrieved after other page content has been loaded'
        ];
    }

    public function defineProperties()
    {
      return [
          'maxItems' => [
              'title'             => 'Max items',
              'description'       => 'How many feed items should be displayed?',
              'default'           => 10,
              'type'              => 'string',
              'validationPattern' => '^[0-9]+$',
              'validationMessage' => 'The Max items property must be numeric'
          ],
          'renderPartial' => [
              'title'             => 'Render partial',
              'description'       => 'The path to the partial that will be used as a template to render feed items. @feed is provided by the plugin itself.',
              'default'           => '@feed',
              'type'              => 'string'
          ]
      ];
    }

    public function onRun()
    {
        $this->page['renderPartial'] = $this->property('renderPartial');
        $this->addJs('/plugins/jasonwilliams/feed/assets/javascript/lazyloadshortfeed.js');
    }

    public function onUpdateRequested()
    {
        date_default_timezone_set('America/Edmonton');
        $this->page['posts'] = FeedItem::orderBy('timestamp', 'desc')->take($this->property('maxItems'))->get();
    }
}