<?php
/*
 * 888888ba                 dP  .88888.                    dP
 * 88    `8b                88 d8'   `88                   88
 * 88aaaa8P' .d8888b. .d888b88 88        .d8888b. .d8888b. 88  .dP  .d8888b.
 * 88   `8b. 88ooood8 88'  `88 88   YP88 88ooood8 88'  `"" 88888"   88'  `88
 * 88     88 88.  ... 88.  .88 Y8.   .88 88.  ... 88.  ... 88  `8b. 88.  .88
 * dP     dP `88888P' `88888P8  `88888'  `88888P' `88888P' dP   `YP `88888P'
 *
 *                          m a g n a l i s t e r
 *                                      boost your Online-Shop
 *
 * -----------------------------------------------------------------------------
 * (c) 2010 - 2021 RedGecko GmbH -- http://www.redgecko.de
 *     Released under the MIT License (Expat)
 * -----------------------------------------------------------------------------
 */

MLFilesystem::gi()->loadClass('Base_Model_Image');

class ML_Shopware_Model_Image extends ML_Base_Model_Image {

    /**
     * @var Shopware\Bundle\MediaBundle\MediaService
     */
    static protected $oShopwareMediaService = null;

    protected function getShopwareMediaService(){
        if(self::$oShopwareMediaService === null){
            self::$oShopwareMediaService = Shopware()->Container()->get('shopware_media.media_service');
        }
        return self::$oShopwareMediaService;
    }

    public function getFallbackUrl($sSrc, $sDst, $iX, $iY) {
        return MLHttp::gi()->getBackendBaseUrl().'/backend/Magnalister/imageResize'.
            '?'.MLHttp::gi()->parseFormFieldName('x').'='.$iX.
            '&'.MLHttp::gi()->parseFormFieldName('y').'='.$iY.
            '&'.MLHttp::gi()->parseFormFieldName('src').'='.$sSrc.
            '&'.MLHttp::gi()->parseFormFieldName('dst').'='.$sDst;
    }


    /**
     * Use Shopware thumbnail generator as fallback, useful by cloud media server.
     * @param $sSrc
     * @param $sType
     * @param $iMaxWidth
     * @param $iMaxHeight
     * @param bool $blUrlOnly
     * @return array|string
     * @throws Exception
     */
    public function resizeImage($sSrc, $sType, $iMaxWidth, $iMaxHeight, $blUrlOnly = false) {
        // prevent duplicate generation of same image in same process
        $imgHash = md5($sSrc.$sType.$iMaxWidth.$iMaxHeight.$blUrlOnly);
        if (array_key_exists($imgHash, self::$cache)) {
            return self::$cache[$imgHash];
        }

        try{
            $return = parent::resizeImage($sSrc, $sType, $iMaxWidth, $iMaxHeight, $blUrlOnly); // TODO: Change the autogenerated stub
        } catch (Exception $oEx) {
            $return = false;
        }

        //as fallback if image resource is in another server
        if($return === false){
            try {
                $sDst = 'magnalister/'.$this->getDestinationPath($sSrc, $sType, $iMaxWidth, $iMaxHeight);
                $sDst2 = $this->getDestinationPath($sSrc, $sType, $iMaxWidth, $iMaxHeight);//in some shopware shop we are not allow to create magnalister directory, so we create image in media directory
                if (!$this->checkImageExistence($this->getImageUrl($sDst))) {
                    if ($this->checkImageExistence($sDst2)) {
                        $sDst = $sDst2;
                    } else {
                        /** @var Shopware\Components\Thumbnail\Generator\Basic $mediaGeneratorService */
                        $mediaGeneratorService = Shopware()->Container()->get('thumbnail_generator_basic');
                        try {
                            $mediaGeneratorService->createThumbnail($sSrc, $sDst, $iMaxWidth, $iMaxHeight, true);
                        } catch (\Throwable $ex1) {//it is not allow to create magnalister directory, so we create image in media directory
                            try {
                                $mediaGeneratorService->createThumbnail($sSrc, $sDst2, $iMaxWidth, $iMaxHeight, true);
                                $sDst = $sDst2;
                            } catch (\Throwable $ex2) {
                                MLMessage::gi()->addDebug('There is problem to create image with this source and destination', array($sSrc, $sDst2));
                                MLMessage::gi()->addDebug($ex2);
                            }
                            MLMessage::gi()->addDebug('There is problem to create image with this source and destination into media server', array($sSrc, $sDst2));
                            MLMessage::gi()->addDebug($ex1);
                        }
                    }
                }
                if ($blUrlOnly) {
                    $return = self::$cache[$imgHash] = $this->getImageUrl($sDst);
                } else {
                    $return = self::$cache[$imgHash] = array(
                        'url' => $this->getImageUrl($sDst),
                        'width' => $iMaxWidth,
                        'height' => $iMaxHeight,
                        'alt' => basename($sSrc)
                    );
                }
            } catch (Exception $oEx) {
//                $line = __FILE__.__LINE__;echo print_m($oEx->getMessage());
            }
        }
        return $return;
    }


    protected function getImageUrl($sPath){
        return  $this->getShopwareMediaService()->getUrl($sPath);
    }


    protected function checkImageExistence($sPath){
        return $this->getimagesize($sPath);
    }


}
