<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class will take care of ADSL Traffic.
 *
 * @package    ADSL
 * @category   Service
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
abstract class Service_Traffic_Adsl {
	protected $aso;
	protected $today;
	protected $fetchresult = NULL;
	protected $curlopts = array(
		CURLOPT_CONNECTTIMEOUT => 60,
		CURLOPT_FAILONERROR => TRUE,
		CURLOPT_FOLLOWLOCATION => FALSE,
		CURLOPT_HEADER => FALSE,
		CURLOPT_HTTPPROXYTUNNEL => FALSE,
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_SSL_VERIFYHOST => FALSE,
		CURLOPT_SSL_VERIFYPEER => FALSE,
		CURLOPT_VERBOSE => FALSE,
	);

	/**
	 * Setup this class. We need to get our supplier details out of the database.
	 */
	public function __construct() {
		// Our DB record must be the suffix of this class name
		$supplier = preg_replace('/^'.get_parent_class($this).'_/','',get_class($this));

		$aso = ORM::factory('ADSL_Supplier')
			->where('name','=',$supplier)
			->find();

		if (! $aso->loaded())
			throw new Kohana_Exception('Supplier :supplier not defined in the database',array(':supplier'=>$supplier));

		$this->aso = $aso;
		$this->today = date('Y-m-d',strtotime('yesterday'));
	}

	/**
	 * Return an instance of this class
	 */
	public static function instance($supplier) {
		$sc = Kohana::classname(get_called_class().'_'.$supplier);

		if (! class_exists($sc))
			throw new Kohana_Exception('Class doesnt exist for :supplier',array(':supplier'=>$supplier));
		else
			return new $sc;
	}

	/**
	 * Traffic data from supplier
	 */
	public function update_traffic() {
		if (Minion_CLI::options('verbose'))
			echo ' - Last: '.date('Y-m-d',strtotime($this->aso->stats_lastupdate.'+1 day'))."\n";

		for ($querydate=date('Y-m-d',strtotime($this->aso->stats_lastupdate.'+1 day'));
			$querydate<=$this->today;
			$querydate=date('Y-m-d',strtotime($querydate.'+1 day'))) {

			if (Minion_CLI::options('verbose'))
				echo " - Date: $querydate\n";

			$goodfetch = false;
			// @todo log this fetch in a "log"

			// Supplier specific output
			// Data returned should be in MB's
			$data = $this->getdata($querydate);

			if (Minion_CLI::options('verbose'))
				print_r($data);

			if (! $this->fetchresult) {
				echo 'Bad fetch'.get_class($this);
				break;
			}

			$traffic = ORM::factory('Service_Plugin_Adsl_Traffic');
			foreach ($data as $item) {
				$traffic->values($item,array_keys($item));
				$traffic->supplier_id = $this->aso->id;

				if ($traffic->check())
					$traffic->save();

				if (! $traffic->saved())
					throw new Kohana_Exception('Unable to save traffic record');

				$traffic->clear();
			}
		}

		if ($this->fetchresult) {
			$this->aso->stats_lastupdate = $this->today;
			$this->aso->save();
		}
	}
}
?>
