<?php

namespace FiloBlu\Flow\Model;

use FiloBlu\Flow\Api\SwatchInterface;
use FiloBlu\Flow\Api\SwatchRepositoryInterface;
use Magento\Framework\App\ResourceConnectionFactory;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Zend_Db_Expr;

/**
 * Class SwatchRepository
 * @package FiloBlu\Flow\Model
 */
class SwatchRepository implements SwatchRepositoryInterface
{

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

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

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


    public function save(SwatchInterface $swatch)
    {
        $connection = $this->getConnection();
        $table = $connection->getTableName('flow_swatch');
        $connection->insert(
            $table,
            [
                'id' => $swatch->getId(),
                'name' => $swatch->getName(),
                'attribute' => $swatch->getAttribute(),
                'option_name' => $swatch->getOptionName(),
                'option_id' => $swatch->getOptionId(),
                'type' => $swatch->getType(),
                'path' => $swatch->getPath(),
                'status' => $swatch->getStatus(),
                'log' => $swatch->getLog(),
                'meta_file' => $swatch->getMetaFile(),
                'meta_insert_time' => $swatch->getMetaInsertTime(),
                'meta_processed' => $swatch->getMetaProcessed()
            ]
        );
    }

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

        return $this->connection;
    }
}
