<?php
/**
 * Webkul Software.
 *
 * @category   Webkul
 * @package    Webkul_Agorae
 * @author     Webkul Software Private Limited
 * @copyright  Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license    https://store.webkul.com/license.html
 */
namespace Webkul\Agorae\Observer;

use Magento\Framework\Event\ObserverInterface;
use Webkul\Agorae\Helper\Data;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Locale\Resolver;

/**
 * Webkul Agorae SaveConfigurationObserver Observer
 */
class SaveConfigurationObserver implements ObserverInterface
{
    /**
     * @var ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Framework\Locale\Resolver
     */
    protected $locale;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $fileSystem;

    /**
     * __construct
     * @param Data                                       $helper
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Filesystem              $fileSystem
     * @param Resolver                                   $locale
     */
    public function __construct(
        Data $helper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        Resolver $locale,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Filesystem $fileSystem
    ) {
        $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $this->_helper = $helper;
        $this->_storeManager = $storeManager;
        $this->locale = $locale;
        $this->messageManager = $messageManager;
        $this->fileSystem = $fileSystem;
    }

    /**
     * MpFavouriteSeller product approve event handler.
     *
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            $deleteDirPath = [
                DirectoryList::STATIC_VIEW => ['frontend/Webkul/agorae/'.$this->locale->getLocale().'/'],
                DirectoryList::TMP_MATERIALIZATION_DIR => ['css/','source/']
            ];
            foreach ($deleteDirPath as $baseDir => $absolutePathArray) {
                foreach ($absolutePathArray as $absolutePath) {
                    $path = $this->filesystem->getDirectoryRead($baseDir)
                            ->getAbsolutePath($absolutePath);
                    if (Magento\Framework\Filesystem\DriverInterface::isDirectory($path)) {
                        $this->_helper->deleteDirectories($path);
                    }
                }
            }
        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
    }
}
