<?php

namespace MageArray\LowerPrice\Block\Adminhtml\Form\Field;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\Data\Form\Element\Factory;
use Magento\Framework\Data\Form\Element\CollectionFactory;
use Magento\Framework\Escaper;

/**
 * Class Export
 * @package MageArray\LowerPrice\Block\Adminhtml\Form\Field
 */
class Export extends AbstractElement
{
    protected $_dataHelper;
    protected $_directoryList;
    protected $_filesystem;
    protected $_mediaDirectory;
    protected $storeManager;
    protected $_file;
    
    public function __construct(
        \Magento\Framework\Filesystem $filesystem,
        \MageArray\LowerPrice\Helper\Data $dataHelper,
        DirectoryList $directoryList,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        Factory $factoryElement,
        CollectionFactory $factoryCollection,
        Escaper $escaper,
        \Magento\Framework\Filesystem\Io\File $file,
        $data = []
    ) {
        parent::__construct($factoryElement, $factoryCollection, $escaper, $data);
        
        $this->_dataHelper = $dataHelper;
        $this->_directoryList = $directoryList;
        $this->_filesystem = $filesystem;
        $this->_mediaDirectory = $filesystem
            ->getDirectoryWrite(
                DirectoryList::MEDIA
            );
        $this->storeManager = $storeManager;
        $this->_file = $file;
    }

    /**
     * @return string
     */
    public function getElementHtml()
    {
        $latestTime = 0;
        $latestFilename = '';
        
        $currentStore = $this->storeManager->getStore();
        $linkUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        
        $file = $this->_dataHelper->getCsvFile();
        if ($this->_file->fileExists($this->_mediaDirectory->getAbsolutePath('lowerprice/csv') . '/' . $file)) {
            $buttonBlock = $this->getForm()->getParent()
                ->getLayout()->createBlock(
                    \Magento\Backend\Block\Widget\Button::Class
                );
                
            $url = $linkUrl . 'lowerprice/csv/'. $file;
                
            $data = [
                'label' => __('Export CSV'),
                'onclick' => "setLocation('" . $url . "')",
                'class' => '',
            ];
            
            return $buttonBlock->setData($data)->toHtml();
            ;
        } else {
            return 'Sorry csv file is not available!';
        }
    }
}
