<?php


namespace Magetop\Advancepreview\Helper;

use Magento\Framework\App\Helper\Context;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\Framework\Json\Helper\Data
     */
    const ENABLE_DEV = true;
    /**
     * @var \Magento\Framework\Json\Helper\Data
     */
    protected $jsonHelper;
    /**
     * @var \Magento\Backend\Model\UrlInterface
     */
    protected $backendUrl;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    protected $httpContext;
    protected $customerFactory;
    protected $customerSession;
    public function __construct(
        Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Backend\Model\UrlInterface $backendUrl,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Model\Session $customerSession

    )
    {
        parent::__construct($context);
        $this->jsonHelper = $jsonHelper;
        $this->backendUrl = $backendUrl;
        $this->storeManager = $storeManager;
        $this->httpContext = $httpContext;
        $this->customerFactory = $customerFactory;
        $this->customerSession = $customerSession;
    }


    /**
     * @param string $field
     * @param bool $isBackend
     * @return mixed
     */
    function getOpdSetting($field, $isBackend = false) {
       /* $filed = $this->scopeConfig->getValue($field,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        if(!$isBackend)
        {
            $filed = $this->scopeConfig->getValue($field,\Magento\Store\Model\ScopeInterface::SCOPE_WEBSITES);
        }
        return $filed;*/
    }

    /**
     * @param array $items
     * @return string
     */
    function convertOpdJsonEncode($items) {
        if(is_array($items) && count($items))
            return $this->jsonHelper->jsonEncode($items);
        return '{}';
    }

    /**
     * @param string $str
     * @return array|mixed
     */
    function convertOpdJsonDecode($str)
    {
        if(trim($str) != '')
            return $this->jsonHelper->jsonDecode($str);
        return array();
    }

    /**
     * @param string $path
     * @param $params
     * @return mixed
     */
    function getOpdAdminUrl($path, $params = array()) {
        $url = $this->backendUrl->getUrl($path, $params);
        return $this->formatOpdAjaxUrl($url);
    }

    /**
     * @param string $url
     * @return string
     */
    function formatOpdAjaxUrl($url) {
        return $url;
    }

    /**
     * @return \Magento\Framework\Json\Helper\Data
     */
    function checkOpdModel () {
        return self::ENABLE_DEV;
    }

    /**
     * @return int
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getOpdCurrentStoreId() {
        return $this->storeManager->getStore()->getId();
    }
    function checkIsProVersion () {
        return $this->_moduleManager->isOutputEnabled('Magetop_Opdpro') ? true : false;
    }
    function checkIsBackend() {
        return false;
    }
    function convertImage($dir,$tmpName,$fileType,$size = 'large') {
        $saveFileType = "png";
        $dir .= '/';
        $imagePath = $dir.$tmpName;
        $image = new \Imagick();
        $fileName = 'image-convert-lg'.time().'.png';
        if($size == 'small')
            $fileName = 'image-convert-sm'.time().'png';
        try {
            $image->readimage($imagePath);
            if($fileType == "psd"){
                $image->setIteratorIndex(0);
            }
            $dimensions = $image->getImageGeometry();
            $width = $dimensions['width'];
            $height = $dimensions['height'];
            if($size == "large"){
                $maxWidth = 720;
                $maxHeight =720;
            }
            if($size == "small"){
                $maxWidth = 250;
                $maxHeight =250;
            }
            if($height > $width){
                //Portrait
                if($height > $maxHeight)
                    $image->thumbnailImage(0, $maxHeight);
                $dimensions = $image->getImageGeometry();
                if($dimensions['width'] > $maxWidth){
                    $image->thumbnailImage($maxWidth, 0);
                }
            }elseif($height < $width){
                //Landscape
                $image->thumbnailImage($maxWidth, 0);
            }else{
                //square
                $image->thumbnailImage($maxWidth, 0);
            }
            if($size == "large"){
                $image->writeImage($dir.$fileName);
            }
            if($size == "small"){
                $image->writeImage($dir.$fileName);
            }
        }
        catch (\Exception $exception) {
            return false;
        }
        return $fileName;

    }
    public function getYourDomain($url)   {
        //$dev = 'dev';
        $dev = $_SERVER['SERVER_NAME'];
        if ( !preg_match("/^http/", $url) )
            $url = 'http://' . $url;
        if ( $url[strlen($url)-1] != '/' )
            $url .= '/';
        $pieces = parse_url($url);
        $domain = isset($pieces['host']) ? $pieces['host'] : '';
        if ( preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs) ) {
            $res = preg_replace('/^www\./', '', $regs['domain'] );
            return $res;
        }
        return $dev;
    }
    function checkImagickInstalled() {
        if(class_exists(\Imagick::class)){
            return true;
        }
        return false;
    }
    /**
     * @return int
     */
    public function getCustomerGroup() {
        $group = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();
            $customer = $this->customerFactory->create()->load($customerId);
            $group = $customer->getGroupId();

        }
        return $group;
    }

    /**
     * @return bool
     */
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
}
