<?php
App::import('Model', 'PushSubscriber');
class PushBehavior extends ModelBehavior {

	# Skip these fields
	private $ignoreList = array(
		'id', 'modified', 'modified_by', 'created', 'created_by', 'slug',
		'ordering', 'filesize', 'mimetype', 'customization'
	);


/**
 * Gets previous state of data before save.
 *
 * @param	Model
 *		Model object.
 * @return
 *		Returns always true.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	function beforeSave(&$Model) {

		# If update
		if (isset($Model->id) && !empty($Model->id)) {
			$this->previousState = $Model->previousData[$Model->alias];
		}

		if(!empty($Model->data[$Model->alias]['is_last_second']) && empty($Model->data[$Model->alias]['is_last_second_desc'])) {
			$Model->validationErrors['is_last_second_desc'] = __('Please provide notification text');
			return false;
		}
		return true;
	}

/**
 * Compare state before and after save and store differences in log.
 *
 * @param	Model
 *		Model object.
 * @param	created
 *		Flag, if set then operation is insert, not update.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	function afterSave($Model, $created) {
		$this->currentState = $Model->data[$Model->alias];

		if($created) {
			if(!empty($this->currentState['is_last_second'])) {
				$pushData = $this->currentState['is_last_second_desc'];
				if(!empty($pushData)) {
					$push = new PushSubscriber();
					$push->pushNotification($pushData);
				} else {
					return false;
				}
				return true;
			}
		}

		if(empty($this->currentState['is_last_second'])) {
			return true;
		}

		$currentValue = $this->currentState['is_last_second'];
		$previousValue = $this->previousState['is_last_second'];

		if(empty($previousValue) && $currentValue == 1) {
			$pushData = $this->currentState['is_last_second_desc'];
			if(!empty($pushData)) {
				$push = new PushSubscriber();
				$push->pushNotification($pushData);
			} else {
				return false;
			}
		}

		return true;
	}
}
