<?php

namespace FiloBlu\Flow\Model;

use FiloBlu\Flow\Api\StockAdjustmentInterface;
use FiloBlu\Flow\Api\StockAdjustmentRepositoryInterface;
use FiloBlu\Flow\Setup\UpgradeSchema;
use Magento\Framework\App\ResourceConnectionFactory;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Zend_Db_Expr;

/**
 * Class StockAdjustmentRepository
 * @package FiloBlu\Flow\Model
 */
class StockAdjustmentRepository implements StockAdjustmentRepositoryInterface
{

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

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

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

    public function save(StockAdjustmentInterface $stockAdjustment)
    {
        $connection = $this->getConnection();
        $table = $connection->getTableName(UpgradeSchema::FLOW_STOCK_ADJUSTMENT_TABLE);
        $connection->insert(
            $table,
            [
                'meta_id' => $stockAdjustment->getMetaId(),
                'sku' => $stockAdjustment->getSku(),
                'warehouse' => $stockAdjustment->getWarehouse(),
                'adjustment' => $stockAdjustment->getAdjustment(),
                'final_quantity' => $stockAdjustment->getFinalQuantity(),
                'source' => $stockAdjustment->getSource(),
                'detail' => $stockAdjustment->getDetail(),
                'meta_ref_id' => $stockAdjustment->getMetaRefId(),
                'meta_file' => $stockAdjustment->getMetaFile(),
                'meta_insert_time' => $stockAdjustment->getMetaInsertTime(),
                'meta_processed' => $stockAdjustment->getMetaProcessed(),
                'meta_process_time' => $stockAdjustment->getMetaProcessedTime()
            ]
        );
    }

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

        return $this->connection;
    }
}
