<?php

namespace FiloBlu\Flow\Model\Channel\In;

use Exception;
use FiloBlu\Flow\Block\Adminhtml\Channel\Edit\Tab\Config;
use FiloBlu\Flow\Helper\LoggerProvider;
use FiloBlu\Flow\Model\Channel\ConfigFactory;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\ObjectManagerInterface;


class Sizeguide extends AbstractModel
{
    /**
     * @var ResourceConnection
     */
    protected $resourceConnection;


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

    /**
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function insertData($data)
    {
        $meta_file_id = $this->getFile()->getId();
        $channelConfig = $this->getChannelConfig()->_mappedData['config'];
        $parser = $this->getParser();

        if ($useMap = $this->getChannelConfig()->usesMap()) {
            if (!isset($this->map) || empty($this->map)) {
                throw  new \RuntimeException('Sizeguide  has option \'use map = yes\' but no map is provided');
            }
            $this->map = $parser->map;
        }

        $flow = $this->getFile()->getData('flow');
        $model = $this->objectManager->create("FiloBlu\Flow\Model\\{$flow}");
        if (!$model) {
            return false;
        }

        if (!$useMap) {
            $connection = $this->resourceConnection->getConnection();
            $table = $connection->getTableName('flow_from_sizeguide');
            $select = $connection->select("row_number")
                ->from($table)
                ->where('meta_file = ' . $meta_file_id)
                ->order('meta_id desc');
            $lastRow = $connection->fetchOne($select);

            if($lastRow !== false) {
                $styleCell = $channelConfig['sizeguide_style_rows_cells'];
                $rowCount = $lastRow+1;
            }
            else {
                $styleCell = $channelConfig['sizeguide_style_cells_header'];
                $rowCount = 0;
            }

            foreach($data as $dataIndex => $rowValue) {
                $tableRow = '<td '.$styleCell.'>'.$rowValue.'</td>';
                $connection->insert('flow_from_sizeguide', array(
                    'row_number' => $rowCount,
                    'row' => '<td '.$styleCell.'>'.$rowValue.'</td>',
                    'meta_file' => $meta_file_id,
                    'meta_processed' => 0,
                    'meta_insert_time' => date('Y-m-d H:i:s')
                ));
            }
        }
        else {
            /* TODO
               in case field mapping is used
               implement the code here
            */
        }
    }

}
