<?php

namespace FiloBlu\Flow\Model;

use FiloBlu\Flow\Api\LogInterface;
use FiloBlu\Flow\Api\LogRepositoryInterface;
use Magento\Framework\App\ResourceConnectionFactory;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Zend_Db_Expr;

/**
 * Class LogRepository
 * @package FiloBlu\Flow\Model
 */
class LogRepository implements LogRepositoryInterface
{

    /** @var AdapterInterface */
    protected $connection;

    /**
     * @var ResourceConnectionFactory
     */
    protected $connectionFactory;

    /**
     * LogRepository constructor.
     * @param ResourceConnectionFactory $connectionFactory
     */
    public function __construct(
        ResourceConnectionFactory $connectionFactory
    ) {
        $this->connectionFactory = $connectionFactory;
    }

    /**
     * @param LogInterface $log
     * @return mixed|void
     */
    public function save(LogInterface $log)
    {
        $connection = $this->getConnection();
        $table = $connection->getTableName('flow_log');
        $connection->insertOnDuplicate(
            $table,
            [
                'id' => $log->getId(),
                'message' => $log->getMessage(),
                'error_severity' => $log->getSeverity(),
                'error_repeat_count' => $log->getErrorRepeatCount() ?: 1,
                'stack_trace' => $log->getStackTrace(),
                'meta_file' => $log->getMetaFile(),
                'meta_insert_time' => $log->getMetaInsertTime(),
                'stack_trace_hash' => $log->getStackTraceHash()
            ],
            [
                'error_repeat_count' => new Zend_Db_Expr('error_repeat_count + 1')
            ]
        );
    }

    /**
     * @return AdapterInterface
     */
    protected function getConnection()
    {
        if ($this->connection === null) {
            $this->connection = $this->connectionFactory->create()->getConnection();
        }

        return $this->connection;
    }
}
