<?php

namespace MageArray\LowerPrice\Model\Config\Source;

/**
 * Class Upload
 * @package MageArray\LowerPrice\Model\Config\Source
 */
class Upload extends \Magento\Config\Model\Config\Backend\File
{
    /**
     * Directory Path Where The Csv File Will Upload
     */
    const UPLOAD_DIR = 'lowerprice/csv';

    /**
     * @return mixed
     */
    public function csvProcessor()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        return $objectManager->create(\Magento\Framework\File\Csv::Class);
    }

    /**
     * @param $sku
     * @return mixed
     */
    public function loadMyProduct($sku)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        return $objectManager->create(\Magento\Catalog\Model\Product::Class)->loadByAttribute('sku', $sku);
    }

    /**
     * @return bool
     */
    protected function _getAllowRenameFiles()
    {
        return true;
    }

    /**
     * @return mixed
     */
    protected function _getUploadDir()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $_file = $objectManager->create(\Magento\Framework\Filesystem\Io\File::Class);
        if (!is_dir(
            $this->_mediaDirectory->getAbsolutePath(
                $this->_appendScopeInfo(self::UPLOAD_DIR)
            )
        )
        ) {
            $_file->mkdir($this->_mediaDirectory->getAbsolutePath(
                $this->_appendScopeInfo(self::UPLOAD_DIR)
            ), 0777, true);
        }
        return $this->_mediaDirectory->getAbsolutePath(
            $this->_appendScopeInfo(self::UPLOAD_DIR)
        );
    }

    /**
     * @return bool
     */
    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
     * @return array
     */
    protected function _getAllowedExtensions()
    {
        return ['csv'];
    }

    /**
     * @return mixed
     */
	// @codingStandardsIgnoreStart
    public function beforeSave()
    {
		// @codingStandardsIgnoreEnd
        $this->uploadAndImport($this);
        $value = $this->getValue();
        $deleteFlag = is_array($value) && !empty($value['delete']);
        $fileTmpName = $this->getValue('tmp_name');
        $oldValue = explode("/", $this->getOldValue());
        $deleteValue = end($oldValue);
        if ($this->getOldValue() && ($fileTmpName || $deleteFlag)) {
            $this->_mediaDirectory->delete(
                $this->_appendScopeInfo(
                    self::UPLOAD_DIR
                ) . '/' . $deleteValue
            );
        }
        return parent::beforeSave();
    }

    /**
     * @param \Magento\Framework\DataObject $object
     * @return $this
     */
    public function uploadAndImport(\Magento\Framework\DataObject $object)
    {
        $main = $object;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $messageManager = $objectManager->create(\Magento\Framework\Message\ManagerInterface::Class);
        try {
            $fileName = $this->getValue('name');
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            if (empty($this->getValue('tmp_name')) || $ext != 'csv') {
                return $this;
            }
            $filePath = $this->getValue('tmp_name');
            $delimiter = $this->getFileDelimiter($filePath);
            $this->csvProcessor()->setDelimiter($delimiter);

            $importProductRawData = $this->csvProcessor()->getData($filePath);
            if (!empty($importProductRawData)) {
                $first = 0;
                $wrongSku = [];
                $successSku = [];
                foreach ($importProductRawData as $dataRow) {
                    $first++;
                    if ($first == 1) {
                        continue;
                    }
                    $product = $this->loadMyProduct($dataRow[0]);
                    if (!empty($product)) {
                        $product->setData('found_lower_price', $dataRow[1]);
                        $product->getResource()->saveAttribute($product, 'found_lower_price');
                        $product->setData('auto_approved_inquiries', $dataRow[2]);
                        $product->getResource()->saveAttribute($product, 'auto_approved_inquiries');
                        $successSku[] = $dataRow[0];
                    } else {
                        $wrongSku[] = $dataRow[0];
                    }
                }

                if (!empty($successSku)) {
                    $messageManager->addSuccess('Product save successful. sku: ' . implode(',', $successSku));
                }

                if (!empty($wrongSku)) {
                    $messageManager->addError('Product not found wrong sku: ' . implode(',', $wrongSku));
                }
            }
        } catch (\Exception $e) {
            $messageManager->addError($e->getMessage());
        }
    }

    /**
     * @param $file
     * @param int $checkLines
     * @return mixed
     */
    public function getFileDelimiter($file, $checkLines = 2)
    {
        $file = new \SplFileObject($file);
        $delimiters = [
            ',',
            '\t',
            ';',
            '|',
            ':'
        ];
        $results = [];
        $i = 0;
        while ($file->valid() && $i <= $checkLines) {
            $line = $file->fgets();
            foreach ($delimiters as $delimiter) {
                $regExp = '/[' . $delimiter . ']/';
                $fields = preg_split($regExp, $line);
                if ($this->getCount($fields) > 1) {
                    if (!empty($results[$delimiter])) {
                        $results[$delimiter]++;
                    } else {
                        $results[$delimiter] = 1;
                    }
                }
            }
            $i++;
        }
        $results = array_keys($results, max($results));
        return $results[0];
    }
    
    public function getCount($data)
    {
        return count($data);
    }
}
