<?php
/**
 * Copyright © 2018 FiloBlu . All rights reserved.
 */

namespace FiloBlu\Flow\Helper;

use FiloBlu\Flow\Model\Channel;
use FiloBlu\Flow\Model\Map;
use FiloBlu\Flow\Model\Processor;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;

/**
 * Class Check
 * @package FiloBlu\Flow\Helper
 */
class Check extends AbstractHelper
{
    /**
     * @var
     */
    protected $_storesByLocale;
    /**
     * @var AdapterInterface
     */
    protected $_connection;

    /**
     * @var FiloBlu\Flow\Helper\Check
     */
    protected $_processor;

    /**
     * @var Map
     */
    protected $_map;

    /**
     * @var
     */
    protected $_file;

    /**
     * @var
     */
    protected $_channel;

    /**
     * @var
     */
    protected $_output_messages;

    /**
     * @var
     */
    protected $_channel_obj;

    /**
     * @var
     */
    protected $_masks;

    /**
     * Check constructor.
     * @param Context $context
     * @param ResourceConnection $_connection
     * @param Processor $processor
     * @param Map $map
     * @param Channel $channel
     */
    public function __construct(
        Context $context,
        ResourceConnection $_connection,
        Processor $processor,
        Map $map,
        Channel $channel
    )
    {
        $this->_connection = $_connection->getConnection();
        $this->_processor = $processor;
        $this->_map = $map;
        $this->_channel_obj = $channel;
        $this->_output_messages = [];
        $this->_masks = [];
        parent::__construct($context);

    }

    /**
     * @param $file
     */
    public function setFile($file)
    {
        $this->_file = $file;
    }

    /**
     * Load Channel Map
     */
    public function loadMap()
    {
        $this->_map->load($this->_channel);
    }

    /**
     * Load Channel
     */
    public function loadChannel()
    {
        $this->_channel_obj->load($this->_channel);
    }

    /**
     * Get Channel
     */
    public function getChannel()
    {
        return $this->_channel_obj;
    }

    /**
     * @param $channel
     */
    public function setChannel($channel)
    {
        $this->_channel = $channel;
        $this->setOutputMessage('Il canale selezionato è il seguente: <strong>' . $channel . '</strong>', true);
    }

    /**
     * @param $msg
     * @param bool $res
     */
    public function setOutputMessage($msg, $res = true)
    {
        $this->_output_messages[] = [
            $msg,
            $res
        ];
    }

    /**
     * Retrieve channel name by filename
     * @return int|string
     */
    public function getChannelName()
    {
        $this->getFilesRegex();
        $filename = $this->_file['name'];

        foreach ($this->_masks as $k => $mask) {
            if ($mask != '##' && !empty($mask)) {
                preg_match($mask, $filename, $matches);
                if (count($matches)) {
                    return $k;
                }
            }
        }
        return '';
    }

    /**
     * Get all channel regex
     */
    public function getFilesRegex()
    {
        foreach ($this->_processor->getChannels() as $k => $ch) {
            $this->_masks[$k] = $ch->getConnector()->getConfig()['regex'];
        }
    }

    /**
     * Check if the number of columns of the file is coerent with map
     */
    public function checkColumns()
    {
        $col_num_file = $this->getNumOfColumns();
        $col_num_map = count($this->_map->getFullMappedData());

        if ($col_num_file != $col_num_map) {
            $this->setOutputMessage('Il numero delle colonne non coincide. Le colonne del file sono: <strong>' . $col_num_file . '</strong> le colonne della mappatura <strong>' . $col_num_map . '</strong>', false);
        } else {
            $this->setOutputMessage('Il numero delle colonne coincide ed è pari a: <strong>' . $col_num_file . '</strong>', true);
        }
    }

    /**
     * @param string $separator
     * @return int|void
     */
    public function getNumOfColumns($separator = ';')
    {
        if (($handle = fopen($this->_file['tmp_name'], "r")) !== false) {
            while ($line = fgetcsv($handle, 1000, $this->_channel_obj['parser']['separator'])) {
                return count($line);
            }
        }
    }

    /**
     * Show map columns
     */
    public function showColumns()
    {
        if (count($this->_map->getFields())) {
            $fields = implode(',', $this->_map->getFields());
            $this->setOutputMessage('Le colonne presenti nella mappatura sono le seguenti: <strong>' . $fields . '</strong>', true);
        } else {
            $this->setOutputMessage('Non ci sono colonne presenti nella mappatura', false);
        }
    }

    /**
     * @return array
     */
    public function getOutputMessage()
    {
        return $this->_output_messages;
    }

}