<?php

namespace FiloBlu\Flow\Model\Channel\In;

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

/**
 * Class Price
 * @package FiloBlu\Flow\Model\Channel\In
 */
class Price extends AbstractModel
{
    protected $helperFlow;

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

    /**
     * @param $data
     * @return bool
     */
    public function insertData($data)
    {
        $flow = $this->getFile()->getData('flow');
        $model = $this->objectManager->create('FiloBlu\Flow\Model' . "\\" . $flow);

        if (!$model) {
            return false;
        }

        $checkMappingCount = $this->getParser()->checkMappingCount();

        $model->setData('meta_file', $this->getFile()->getId());
        $model->setData('sku', $data['sku']);

        // No check mapping count, working as CSV headers -> table columns
        if (!$checkMappingCount || $this->map->isDirectInsert()) {
            // No map is checked here
            $this->directInsert($data, $model);
            // Do not go further
            return true;
        }

        foreach ($data as $field => $value) {
            if(!$this->getChannelConfig()->getAllowProcessZeroPrices()) {
                if (in_array(strtolower($field), ['price', 'prezzo']) && (float)$value <= 0) {
                    continue;
                }
            }
            $fieldMap = $this->map->get($field);

            //devo inserire una riga per ogni website/prezzo
            if ((!isset($fieldMap['skip']) || !$fieldMap['skip']) && $fieldMap['type'] === 'price') {
                if (isset($fieldMap['website']) && is_array($fieldMap['website']) && count($fieldMap['website']) > 0) {
                    $websites = $fieldMap['website'];

                    foreach ($websites as $website) {
                        try {
                            $currency = $fieldMap['currency'];
                            $model->setId(null);
                            $model->setData('prezzo', floatval($value));
                            $model->setData('paese', $website);
                            $model->setData('valuta', $currency);
                            $model->setData('meta_processed', 0);
                            $model->setData('meta_insert_time', date('Y-m-d H:i:s'));
                            $model->save();
                        } catch (Exception $e) {
                            $this->_logger->info('Exception! ' . $e->getMessage() . PHP_EOL);
                        }
                    }
                } elseif (isset($fieldMap['website']) && $fieldMap['website'] !== '') {
                    try {
                        $currency = $fieldMap['currency'];
                        $website = $fieldMap['website'];
                        $model->setId(null);
                        $model->setData('prezzo', (float)$value);
                        $model->setData('paese', $website);
                        $model->setData('valuta', $currency);
                        $model->setData('meta_processed', 0);
                        $model->setData('meta_insert_time', date('Y-m-d H:i:s'));
                        $model->save();

                        // $this->_logger->info('Saved!! '. print_r($model->getData(), true) . PHP_EOL);
                    } catch (Exception $e) {
                        $this->_logger->info('Exception! ' . $e->getMessage() . PHP_EOL);
                    }
                } else {
                    $websites_list = explode(',', $data['paese']);

                    try {
                        if (empty($websites_list)) {
                            $this->_logger->info(' no website found for : ' . $data['sku'] . PHP_EOL);
                            return false;
                        }

                        foreach ($websites_list as $website) {
                            $metaProcessed = 0;
                            if (!$this->helperFlow->websiteExist($website)) {
                                $metaProcessed = 2;
                            }
                            $model->setId(null);
                            $model->setData('prezzo', (float)$value);
                            $model->setData('paese', $website);
                            $model->setData('valuta', $data['valuta']);
                            $model->setData('meta_processed', $metaProcessed);
                            $model->setData('meta_insert_time', date('Y-m-d H:i:s'));
                            $model->save();
                        }

                        // $this->_logger->info('Saved!! '. print_r($model->getData(), true) . PHP_EOL);
                    } catch (Exception $e) {
                        $this->_logger->info('Exception! ' . $e->getMessage() . PHP_EOL);
                    }
                }
            }
        }
    }

    /**
     * @param $data
     * @param $model
     */
    private function directInsert($data, $model)
    {
        try {
            foreach ($data as $field => $value) {
                $model->setData($field, $value);
            }
            $model->setData('meta_processed', 0);
            $model->setData('meta_insert_time', date('Y-m-d H:i:s'));
            $model->save();
        } catch (Exception $e) {
            $this->_logger->info('Exception! ' . $e->getMessage() . PHP_EOL);
        }
    }
}
