<?php
/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/

class XenCentral_AdServer_Helper_Attributes_Country extends XenCentral_AdServer_Helper_Attributes_Abstract
{
    protected function _getColumn()
    {
        return 'ip_address';
    }

    public function getLabelFromData($data)
    {
        $label=parent::getLabelFromData($data);
        if($label=='n_a') {
            return new XenForo_Phrase('n_a');
        }
        return $label;
    }


    public function parseData($data)
    {
        $parsedData=array();
        foreach($data AS  $dataRow) {
            if(!$dataRow['ip_address']) {
                $label='n_a';
            } else {
                $dataRow['ip_address']=XenForo_Helper_Ip::convertIpBinaryToString($dataRow['ip_address']);
                $label=$this->_getCountryFromIp($dataRow['ip_address']);
            }
            if(is_object($label)) {
                $label.='';
            }
            if(isset($parsedData[$label])) {
                $parsedData[$label]['count']+=$dataRow['count'];
            } else {
                $parsedData[$label]=array(
                    'ip_address'=>$label,
                    'count'=>$dataRow['count']
                );
            }
        }

        usort($parsedData, array($this, '_sortByCount'));

        return $parsedData;
    }

    protected function _needsSqlOrdering()
    {
        return false;
    }

    protected function _getCountryFromIp($ip)
    {
        if(is_long($ip)) {
            $ip=long2ip($ip);
        }

        return $this->_getGeoCodingModel()->getCountry($ip);
    }

    protected function _sortByCount($item1, $item2)
    {
        if($item1['count'] == $item2['count']) {
            if($item1['ip_address']=='n_a') {
                return 1;
            } else if($item2['ip_address']=='n_a') {
                return -1;
            }
            return strnatcmp($item1['ip_address'], $item2['ip_address']);
        }

        return $item1['count']<$item2['count'];
    }

    /**
     * @return XenCentral_Framework_Model_GeoCoding
     */
    protected function _getGeoCodingModel()
    {
        return $this->_getModelFromCache('XenCentral_Framework_Model_GeoCoding');
    }
}