<?php

namespace Velis\Bpm\Workflow\Handler;

use Exception;
use Velis\App;
use Velis\Bpm\Ticket\Post;
use Velis\Bpm\Ticket\Ticket;
use Velis\Exception as VelisException;
use Velis\Model\DataObject\NoColumnsException;

/**
 * Ticket post context trait
 * @author Damian Kurek <damian.kurek@velis.pl>
 */
trait TicketContextPostTrait
{
    /**
     * Related ticket object
     * @var Ticket
     */
    protected $_ticket;


    /**
     * Event additional data
     * @var mixed
     */
    protected $_additionalData;


    /**
     * Returns action's context post instance
     * @return Post
     * @throws VelisException
     * @throws NoColumnsException
     * @throws Exception
     */
    protected function _getPost(): Post
    {
        if (is_array($this->_additionalData) && $this->_additionalData['post'] instanceof Post) {
            $post = $this->_additionalData['post'];
        } elseif ($this->_ticket->getCurrentPost()) {
            $post = $this->_ticket->getCurrentPost();
        } else {
            $post = null;
        }

        if (!$post) {
            $post = new Post([
                'ticket_id' => $this->_ticket->id(),
                'user_id' => App::$user->id() ?: $this->_ticket['owner_user_id'],
                'person_id' => App::$user->id() ?: $this->_ticket['owner_user_id'],
                'ticket_post_visibility_id' => Post::TYPE_PROTECTED,
            ]);
            $post->add(true);
            $post->setTicket($this->_ticket);
            $this->_additionalData['post'] = $post;
            $this->_ticket->setCurrentPost($post);
        }

        return $post;
    }
}
