<?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_ThemeConfig_Model_Observer 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);
		$this->_getSprite(str_replace('#', '', $configVars['primaryColor']));
		$this->_getStars(str_replace('#', '', $configVars['starColor']));
	}

	protected function _getConfigVariables()
	{
		$websiteId = Mage::app()->getFrontController()->getRequest()->getParam('website');
		$storeId = Mage::app()->getFrontController()->getRequest()->getParam('store');
		$configVars = array();
		$configVarFormat = array(
			'headerFont' => 'avalanche_config/avalanche_design/avalanche_headerfont',
			'bodyFont' => 'avalanche_config/avalanche_design/avalanche_bodyfont',
			'primaryColor' => 'avalanche_config/avalanche_design/avalanche_primarycolor',
			'secondaryColor' => 'avalanche_config/avalanche_design/avalanche_secondarycolor',
			'pageBackground' => 'avalanche_config/avalanche_design/avalanche_background',
			'borderRadius' => 'avalanche_config/avalanche_design/avalanche_borderradius',
			'starColor' => 'avalanche_config/avalanche_design/avalanche_starcolor',
			'googleFonts' => ''
		);

		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['borderRadius'] .= 'px';

		if(strpos($configVars['headerFont'], 'Helvetica') === false && strpos($configVars['headerFont'], 'Lucida Grande') === false) {
			$configVars['googleFonts'] .= $configVars['headerFont'] . ':Regular,Bold';
			$configVars['headerFont'] .= ',Arial,Helvetica,sans-serif';
		} else {
			$fontFamily = explode('/', $configVars['headerFont']);
			$configVars['headerFont'] = '';
			foreach($fontFamily as $font) {
				if($configVars['headerFont'] != '')
					$configVars['headerFont'] .= ', ';
				$configVars['headerFont'] .= $font;
			}
		}
		if(strpos($configVars['bodyFont'], 'Helvetica') === false && strpos($configVars['bodyFont'], 'Lucida Grande') === false && $configVars['bodyFont'] != $configVars['headerFont']) {
			if($configVars['googleFonts'] != '')
				$configVars['googleFonts'] .= '|';
			$configVars['googleFonts'] .= $configVars['bodyFont'] . ':Regular,Bold';
			$configVars['bodyFont'] .= ',Arial,Helvetica,sans-serif';
		} else {
			$fontFamily = explode('/', $configVars['bodyFont']);
			$configVars['bodyFont'] = '';
			foreach($fontFamily as $font) {
				if($configVars['bodyFont'] != '')
					$configVars['bodyFont'] .= ', ';
				$configVars['bodyFont'] .= $font;
			}
		}

        if(empty($configVars['googleFonts'])) {
            unset($configVars['googleFonts']);
        }

		return $configVars;
	}

    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() . '/' . $this->_getTheme() . '/css/';
            $cssTargetBase = Mage::getBaseDir('skin') . '/frontend/' . $this->_getPackage() . '/' . $this->_getTheme() . '/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_config/avalanche_design/avalanche_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());
        }

	}

	protected function _getSprite($hex)
	{
		try {
			$ch = curl_init('http://fastdivision.com/services/avalanche/customization/sprite.php?type=sprite&hex=' . $hex);
			$fp = fopen(Mage::getBaseDir('skin') . '/frontend/avalanche/default/images/sprite.png', 'wb');
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_exec($ch);
			curl_close($ch);
			fclose($fp);
		} catch (exception $ex) {
			Mage::getSingleton('adminhtml/session')->addException($ex,
                Mage::helper('adminhtml')->__('An error occurred while recoloring the sprite:') . ' '
                . $ex->getMessage());			
		}
	}

	protected function _getStars($hex)
	{
		try {
			$ch = curl_init('http://fastdivision.com/services/avalanche/customization/sprite.php?type=stars&hex=' . $hex);
			$fp = fopen(Mage::getBaseDir('skin') . '/frontend/avalanche/default/images/stars.png', 'wb');
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_exec($ch);
			curl_close($ch);
			fclose($fp);
		} catch (exception $ex) {
			Mage::getSingleton('adminhtml/session')->addException($ex,
                Mage::helper('adminhtml')->__('An error occurred while recoloring the rating stars:') . ' '
                . $ex->getMessage());			
		}		
	}
}