<?php

namespace FiloBlu\Flow\Model;

use FiloBlu\Flow\Api\DocumentInterface;
use FiloBlu\Flow\Api\DocumentRepositoryInterface;
use Magento\Framework\App\ResourceConnectionFactory;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Zend_Db_Expr;

/**
 * Class DocumentRepository
 * @package FiloBlu\Flow\Model
 */
class DocumentRepository implements DocumentRepositoryInterface
{

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

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

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


    public function save(DocumentInterface $document)
    {
        $connection = $this->getConnection();
        $table = $connection->getTableName('flow_document');
        $connection->insert(
            $table,
            [
                'id' => $document->getId(),
                'name' => $document->getName(),
                'mime' => $document->getMime(),
                'source' => $document->getSource(),
                'destination' => $document->getDestination(),
                'status' => $document->getStatus(),
                'meta_file' => $document->getMetaFile(),
                'meta_insert_time' => $document->getMetaInsertTime(),
                'meta_processed' => $document->getMetaProcessed()
            ]
        );
    }

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

        return $this->connection;
    }
}
