<?php
/**
 * Avalanche for Magento 1.8+
 * Designed by Fast Division (http://fastdivision.com)
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the EULA
 * that is bundled with this package in the file license.txt.
 * It is also available through the world-wide-web at this URL:
 * http://fastdivision.com/legal/license.txt
 *
 * @author     Fast Division
 * @version    1.5.0
 * @copyright  Copyright 2013 Fast Division
 * @license    http://fastdivision.com/legal/license.txt
 */

require_once(Mage::getBaseDir('skin') . '/frontend/avalanche/default/css/framework/lessc.inc.php');

class FastDivision_Mobile_Model_Observer_Style extends Varien_Object 
{
  protected $configData;
  protected $configWebsiteData;
  protected $configStoreData;
  protected $currentWebsiteName;
  protected $currentStoreName;
  protected $configVars;

	public function saveConfig($observer) 
	{
		$configVars = $this->_getConfigVariables();
		$this->_getStyle($configVars);

		try {
			$touchIconUrl = Mage::getBaseDir('media') . DS . 'touch_icons' . DS . Mage::getStoreConfig('avalanche_mobile/design/touch_icon');
			$this->_resizeTouchIcons($touchIconUrl);
			$splashScreenUrl = Mage::getBaseDir('media') . DS . 'splash_screens' . DS . Mage::getStoreConfig('avalanche_mobile/design/splash_screen');
			$this->_resizeSplashScreen($splashScreenUrl);
		} catch (exception $ex) {
			Mage::getSingleton('adminhtml/session')->addException($ex,
                Mage::helper('adminhtml')->__('An error occurred while resizing the touch icons:') . ' '
                . $ex->getMessage());
		}
	}

	protected function _getConfigVariables()
	{
		$websiteId = Mage::app()->getFrontController()->getRequest()->getParam('website');
		$storeId = Mage::app()->getFrontController()->getRequest()->getParam('store');
		$configVars = array();
		$configVarFormat = array(
			'logo' => 'avalanche_mobile/design/logo',
			'logoRetina' => 'avalanche_mobile/design/logo_retina',
			'primaryColor' => 'avalanche_mobile/design/primarycolor',
			'secondaryColor' => 'avalanche_mobile/design/secondarycolor'
		);

		if(empty($storeId)) {
			if(empty($websiteId)) {
				// Get default store config
				foreach($configVarFormat as $key => $format) {
					$configVars[$key] = Mage::getStoreConfig($format);
				}
			} else {
				// Get store config based on website
				foreach($configVarFormat as $key => $format) {
					$configVars[$key] = Mage::app()->getWebsite($websiteId)->getConfig($format);
				}
			}
		} else {
			// Get store config based on store
			foreach($configVarFormat as $key => $format) {
				$configVars[$key] = Mage::getStoreConfig($format, $storeId);
			}
		}

		$configVars['logo'] = '"' . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . 'media/logos/' . $configVars['logo'] . '"';
		$configVars['logoRetina'] = '"' . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . 'media/logos/' . $configVars['logoRetina'] . '"';
		
		return $configVars;
	}

	protected function _resizeTouchIcons($touchIconPath)
	{
		$resizeDimensions = array('72x72', '57x57');

		foreach($resizeDimensions as $dimensions) {
			$resizePath = Mage::getBaseDir('media') . DS . 'touch_icons' . DS . str_replace('.' . $this->_getFileExtension(Mage::getStoreConfig('avalanche_mobile/design/touch_icon')), '_' . $dimensions . '.' . $this->_getFileExtension(Mage::getStoreConfig('avalanche_mobile/design/touch_icon')), Mage::getStoreConfig('avalanche_mobile/design/touch_icon'));
			$dimensions = explode('x', $dimensions);

			if(!file_exists($resizePath) && file_exists($touchIconPath)):
			    $imageObj = new Varien_Image($touchIconPath);
			    $imageObj->constrainOnly(TRUE);
			    $imageObj->keepAspectRatio(TRUE);
			    $imageObj->keepFrame(FALSE);
			    $imageObj->resize($dimensions[0], $dimensions[1]);
			    $imageObj->save($resizePath);
			endif;
		}
	}

	protected function _resizeSplashScreen($splashScreenPath)
	{
		$resizeDimensions = array('320x460');

		foreach($resizeDimensions as $dimensions) {
			$resizePath = Mage::getBaseDir('media') . DS . 'splash_screens' . DS . str_replace('.' . $this->_getFileExtension(Mage::getStoreConfig('avalanche_mobile/design/splash_screen')), '_' . $dimensions . '.' . $this->_getFileExtension(Mage::getStoreConfig('avalanche_mobile/design/splash_screen')), Mage::getStoreConfig('avalanche_mobile/design/splash_screen'));
			$dimensions = explode('x', $dimensions);

			if(!file_exists($resizePath) && file_exists($splashScreenPath)):
			    $imageObj = new Varien_Image($splashScreenPath);
			    $imageObj->constrainOnly(TRUE);
			    $imageObj->keepAspectRatio(TRUE);
			    $imageObj->keepFrame(FALSE);
			    $imageObj->resize($dimensions[0], $dimensions[1]);
			    $imageObj->save($resizePath);
			endif;
		}		
	}

	protected function _getFileExtension($file_name)
	{
		return substr(strrchr($file_name, '.'), 1);
	}

 protected function _loadConfigData()
  {
      $configDefaultDataObject = Mage::getModel('adminhtml/config_data')
              ->setSection('design');
      $configWebsiteDataObject = Mage::getModel('adminhtml/config_data')
              ->setSection('design')
              ->setWebsite(Mage::app()->getFrontController()->getRequest()->getParam('website', ''));
      $configStoreDataObject = Mage::getModel('adminhtml/config_data')
              ->setSection('design')
              ->setWebsite(Mage::app()->getFrontController()->getRequest()->getParam('website', ''))
              ->setStore(Mage::app()->getFrontController()->getRequest()->getParam('store', ''));

      $this->configData = $configDefaultDataObject->load();
      $this->configWebsiteData = $configWebsiteDataObject->load();
      $this->configStoreData = $configStoreDataObject->load();
      $this->currentWebsiteName = Mage::app()->getFrontController()->getRequest()->getParam('website', '');
      $this->currentStoreName = Mage::app()->getFrontController()->getRequest()->getParam('store', '');
  }

  public function _getPackage()
  {
      if(empty($this->configData)) {
          $this->_loadConfigData();
      }

      if(isset($this->configStoreData['design/package/name'])) {
          $currentPackage = $this->configStoreData['design/package/name'];
      } elseif(isset($this->configWebsiteData['design/package/name'])) {
          $currentPackage = $this->configWebsiteData['design/package/name'];
      } else {
          $currentPackage = $this->configData['design/package/name'];
      }

      $supportedPackages = array('avalanche', 'comet');

      if(in_array($currentPackage, $supportedPackages)) {
          return $currentPackage;
      } else {
          return 0;
      }
  }

  public function _getTheme()
  {
      if(empty($this->configData)) {
          $this->_loadConfigData();
      }

      if(isset($this->configStoreData['design/theme/default'])) {
          $currentTheme = $this->configStoreData['design/theme/default'];
      } elseif(isset($this->configWebsiteData['design/theme/default'])) {
          $currentTheme = $this->configWebsiteData['design/theme/default'];
      } else {
          $currentTheme = $this->configData['design/theme/default'];
      }

      if(empty($currentTheme)) {
          throw new exception('Set a default theme for this store.');
      }

      return $currentTheme;
  }

  protected function _getStyleName()
  {
  	if(empty($this->configData)) {
  		$this->_loadConfigData();
  	}

  	$cssFileName = '';
  	$cssFileName .= (!empty($this->currentWebsiteName)) ? $this->currentWebsiteName . '-' : 'defaultwebsite-';
  	$cssFileName .= (!empty($this->currentStoreName)) ? $this->currentStoreName : 'defaultstore';
  	$cssFileName .= '.css';

  	return $cssFileName;
  }

  protected function _getScope()
  {
      if (Mage::app()->getFrontController()->getRequest()->getParam('store')) {
          $scope   = 'stores';
          $scopeId = (int)Mage::getConfig()->getNode('stores/' . Mage::app()->getFrontController()->getRequest()->getParam('store') . '/system/store/id');
          $scopeCode = Mage::app()->getFrontController()->getRequest()->getParam('store');
      } elseif (Mage::app()->getFrontController()->getRequest()->getParam('website')) {
          $scope   = 'websites';
          $scopeId = (int)Mage::getConfig()->getNode('websites/' . Mage::app()->getFrontController()->getRequest()->getParam('website') . '/system/website/id');
          $scopeCode = Mage::app()->getFrontController()->getRequest()->getParam('website');
      } else {
          $scope   = 'default';
          $scopeId = 0;
          $scopeCode = '';
      }
      $this->setScope($scope);
      $this->setScopeId($scopeId);
      $this->setScopeCode($scopeCode);
  }

	protected function _getStyle($configVars)
	{
        try {
            $cssBase = Mage::getBaseDir('skin') . '/frontend/' . $this->_getPackage() . '/mobile/css/';
            $cssTargetBase = Mage::getBaseDir('skin') . '/frontend/' . $this->_getPackage() . '/mobile/css/';
            $cssTargetFile = $this->_getStyleName();

            if(!file_exists($cssTargetBase . $cssTargetFile)) {
                $createFile = fopen($cssTargetBase . $cssTargetFile, 'x');
                if($createFile) {
                    fclose($createFile);
                } else {
                    throw new exception($cssTargetBase . ' is not writable. Please CHMOD this folder to 777.');
                }
            }

            if(!is_writable($cssTargetBase . $cssTargetFile)) {
                throw new exception($cssTargetBase . $cssTargetFile . ' is not writable. Please CHMOD this file to 777.');
            }

            // Check to see if style.less file is available in theme folder or default (fallback to default)
            if(!file_exists($cssBase . 'style.less')) {
            	$cssBase = Mage::getBaseDir('skin') . '/frontend/' . $this->_getPackage() . '/default/css/';
            	if(!file_exists($cssBase . 'style.less')) {
            		throw new exception('Style.less was not found in your theme or the default package theme.');
            	}
            }

            $lc = new lessc($cssBase . 'style.less');       
            $lessCss = file_get_contents($cssBase . 'style.less');
            $output = $lc->parse($lessCss, $configVars);
            file_put_contents($cssTargetBase . $cssTargetFile, $output);

            $this->_getScope();
            $theme_config = new Mage_Core_Model_Config();
            $theme_config->saveConfig('avalanche_mobile/design/css_path', $cssTargetFile, $this->getScope(), $this->getScopeId());

            Mage::getSingleton('adminhtml/session')->addSuccess('Saved: ' . $cssTargetBase . $cssTargetFile);

        } catch (exception $ex) {
            Mage::getSingleton('adminhtml/session')->addException($ex,
                Mage::helper('adminhtml')->__('An error occurred while exporting the stylesheet:') . ' '
                . $ex->getMessage());
        }

	}
}