<?php
App::uses('SeoCustomGenerator', 'Seo.Model/MetaGenerators');

class SeoGeneratorFactory {

# ~ Generate tags after save - - - - - - - - - - - - - - - - - - - - - - - - - #
	public static function afterSaveGeneration($Model) {
		if(isset($Model->data[$Model->alias]['meta']) && !empty($Model->data[$Model->alias]['meta'])) {
			$generator = self::getGenerator($Model->data[$Model->alias]['meta']);
		} else {
			App::uses('SeoCustomGenerator', 'Seo.Model/MetaGenerators');
			$generator = new SeoCustomGenerator();
		}

		$additionalTags = self::getAdditionalTags($Model);
		return $generator->generateAfterSave($Model, $additionalTags);
	}


# ~ Generate metatags on runtime - - - - - - - - - - - - - - - - - - - - - - - #
	public static function onRuntimeGeneration($page, $request, $allTags) {
		$metaSource = $page['Page']['type'] == 'Module' ? $page['Data'] : $page;
		$metaSource = reset($metaSource);
		$generator = !empty($metaSource['meta']) ? self::getGenerator($metaSource['meta']) : new SeoCustomGenerator();
		if($generator) {
			return $generator->generateAtRuntime($page, $allTags, $request);
		}
		return $allTags;
	}


# ~ Merge additional tags with global tags - - - - - - - - - - - - - - - - - - #
	protected static function getAdditionalTags($Model) {
		if(!isset($Model->data['Seo']['metatag']) || empty($Model->data['Seo']['metatag'])) {
			return array();
		}
		return $Model->data['Seo']['metatag'];
	}


# ~ Get generator- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	protected static function getGenerator($generator = 'generic') {
		# Build generator class name
		$generatorClass = 'Seo' . ucfirst($generator) . 'Generation';

		# Load class
		App::uses($generatorClass, 'Seo.Model/MetaGenerators/Generators');

		# If there is no such class, return null
		if(!class_exists($generatorClass)) {
			return null;
		}

		return new $generatorClass();
	}
}
?>
