<?php
/*
Plugin Name: Map location shortcode
Description: Create a map inline in your posts, via a simple shortcode.
Plugin URI: http://premium.wpmudev.org/project/wordpress-google-maps-plugin
Version: 1.0
Author: Ve Bailovity (Incsub)
*/

class Agm_Map_LocationShortcode {

	private function __construct () {}

	public static function serve () {
		$me = new Agm_Map_LocationShortcode;
		$me->_add_hooks();
	}

	private function _add_hooks () {
		add_shortcode('location', array($this, 'process_location'));
	}

	public function process_location ($args=array(), $content='') {
		$location_args = shortcode_atts(array(
			"coordinates" => false,
			"address" => false,
		), $args);
		if (!array_filter($location_args)) return $content;

		if (!empty($location_args["coordinates"])) return $this->_map_from_coordinates($location_args["coordinates"], $args, $content);
		if (!empty($location_args["address"])) return $this->_map_from_address($location_args["address"], $args, $content);
		return $content;
	}

	private function _map_from_coordinates ($coordinates, $args=array(), $content=false) {
		$key = md5(serialize($args));
		$map_id = get_option($key, false);

		if (!$map_id) {
			list($lat,$lng) = array_map('trim', explode(',', $coordinates));
			if (empty($lat) || empty($lng)) return $content;

			$model = new AgmMapModel;
			$map_id = $model->autocreate_map(false, $lat, $lng, false);

			if (!$map_id) return $content;
			update_option($key, $map_id);
		}

		$args['id'] = $map_id;
		$codec = new AgmMarkerReplacer;
		return $codec->process_tags($args, $content);
	}

	private function _map_from_address ($address, $args=array(), $content=false) {
		$key = md5(serialize($args));
		$map_id = get_option($key, false);

		if (!$map_id) {
			$model = new AgmMapModel;
			$map_id = $model->autocreate_map(false, false, false, $address);

			if (!$map_id) return $content;
			update_option($key, $map_id);
		}

		$args['id'] = $map_id;
		$codec = new AgmMarkerReplacer;
		return $codec->process_tags($args, $content);
	}
}

Agm_Map_LocationShortcode::serve();