<?php

/**
 * @package    Grav\Common\Page
 *
 * @copyright  Copyright (C) 2015 - 2020 Trilby Media, LLC. All rights reserved.
 * @license    MIT License; see LICENSE file for details.
 */

namespace Grav\Common\Page\Medium;

use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;

class Link implements RenderableInterface, MediaLinkInterface
{
    use ParsedownHtmlTrait;

    /** @var array */
    protected $attributes = [];
    /** @var MediaObjectInterface */
    protected $source;

    /**
     * Construct.
     * @param array  $attributes
     * @param MediaObjectInterface $medium
     */
    public function __construct(array $attributes, MediaObjectInterface $medium)
    {
        $this->attributes = $attributes;

        $source = $medium->reset()->thumbnail('auto')->display('thumbnail');

        // FIXME: Thumbnail can be null, maybe we should not allow that?
        if (null === $source) {
            throw new \RuntimeException('Media has no thumbnail set');
        }

        $source->set('linked', true);

        $this->source = $source;
    }

    /**
     * Get an element (is array) that can be rendered by the Parsedown engine
     *
     * @param  string|null  $title
     * @param  string|null  $alt
     * @param  string|null  $class
     * @param  string|null  $id
     * @param  bool $reset
     * @return array
     */
    public function parsedownElement($title = null, $alt = null, $class = null, $id = null, $reset = true)
    {
        $innerElement = $this->source->parsedownElement($title, $alt, $class, $id, $reset);

        return [
            'name' => 'a',
            'attributes' => $this->attributes,
            'handler' => is_array($innerElement) ? 'element' : 'line',
            'text' => $innerElement
        ];
    }

    /**
     * Forward the call to the source element
     *
     * @param string $method
     * @param mixed $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        $object = $this->source;
        $callable = [$object, $method];
        if (!is_callable($callable)) {
            throw new \BadMethodCallException(get_class($object) . '::' . $method . '() not found.');
        }

        $this->source = call_user_func_array($callable, $args);

        // Don't start nesting links, if user has multiple link calls in his
        // actions, we will drop the previous links.
        return $this->source instanceof MediaLinkInterface ? $this->source : $this;
    }
}
