<?php

namespace Velis\Bpm\Workflow\Handler;

use Exception;
use Psr\SimpleCache\InvalidArgumentException;
use Velis\App;
use Velis\Bpm\Workflow;
use Velis\Bpm\Workflow\Handler;
use Velis\Bpm\Workflow\Notification;
use Velis\Bpm\Workflow\Subject;
use Velis\Filter;
use Velis\Lang;
use Velis\ParameterBag;

/**
 * Email message workflow handler
 * @author Olek Procki <olo@velis.pl>
 */
class Email extends Handler
{
    /**
     * Handler execution method
     *
     * @param Subject $subject
     * @param mixed $additionalData
     * @throws \Velis\Exception
     * @throws InvalidArgumentException
     */
    public function run($subject, $additionalData): void
    {
        $params = new ParameterBag($this->getArrayCopy());
        $userProvider = App::getService('userProvider');
        $recipientProvider = new Workflow\Utils\EmailRecipientProvider($userProvider);
        $recipients = $recipientProvider->getRecipients($params, $subject);

        $this['subject'] = Filter::filterStripTags($subject->translatePlaceholders($this['subject']));
        $this['body'] = Filter::filterTextile($this['body']);
        $this['body'] = $subject->translatePlaceholders($this['body']);

        if ($recipients) {
            $notification = new Notification(
                $this['subject'],
                $this['body']
            );

            try {
                $notification->send($recipients);
                $this->success($subject, $additionalData);
            } catch (Exception $e) {
                $this->error($subject, $additionalData, $e);
            }
        } else {
            $this->notice(
                $subject,
                $additionalData,
                'Recipient not found'
            );
        }
    }

    /**
     * Returns parameters reflection info
     * @return array
     */
    public static function getParamsReflection(): array
    {
        return [
            'user_id' => [
                'label' => Lang::get('GENERAL_USER'),
                'type'  => Workflow::PARAM_USER,
            ],

            'subject' => [
                'label' => Lang::get('GENERAL_SUBJECT'),
                'type'  => Workflow::PARAM_STRING,
            ],

            'body' => [
                'label' => Lang::get('GENERAL_CONTENT'),
                'type'  => Workflow::PARAM_TEXT,
            ],
        ];
    }
}
