<?php

namespace FiloBlu\Flow\Model\Channel\In;

use Exception;
use FiloBlu\Flow\Helper\DbTable;
use FiloBlu\Flow\Helper\LoggerProvider;
use FiloBlu\Flow\Model\Channel\ConfigFactory;
use FiloBlu\Flow\Model\Processor;
use Magento\Framework\ObjectManagerInterface;

use function array_key_exists;

class Table extends AbstractModel
{
    /**
     * @var string
     */
    const STATUS_RECEIVED = 'received';

    /**
     * @var string
     */
    const STATUS_PROCESSED = 'processed';

    /**
     * @var string
     */
    const STATUS_PARSED = 'parsed';

    /**
     * @var string
     */
    const STATUS_ERROR = 'error';
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $resourceConnection;

    public function __construct(
        LoggerProvider $loggerProvider ,
        ConfigFactory $channelConfigFactory ,
        ObjectManagerInterface $objectManager,
        \Magento\Framework\App\ResourceConnection $resourceConnection
    )
    {
        parent::__construct($loggerProvider , $channelConfigFactory , $objectManager);
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * @throws \Exception
     */
    public function insertData($data)
    {
        if (array_key_exists( 'field', $data)) {
            unset($data['field']);
        }

        $configData = $this->getChannelConfig()->getConfigData();

        $connection = $this->resourceConnection->getConnection();
        $tableName = $configData['config']['db_table_name'];

        $flow = $this->getFile();

        if (!$data['value']) {
            $flow->setRetry(1)->save();
            throw new Exception('Value is null.');
        }

        $data['creation_date'] = date('Y-m-d H:i:s');

        try {
            $connection->insertMultiple($tableName , $data);

        } catch (Exception $e) {
            $flow->setRetry(1)->save();
            throw new Exception($e->getMessage());
        }

        $flow->setStatus(self::STATUS_PROCESSED)->save();
    }
}
