#!/usr/bin/env python
#
# Copyright (c) 2010-2012 Appcelerator, Inc. All Rights Reserved.
# Licensed under the Apache Public License (version 2)

import os, sys, re

this_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(this_dir, "..")))

from common import dict_has_non_empty_member, strip_tags, not_real_titanium_types, to_ordered_dict

android_support_dir = os.path.abspath(os.path.join(this_dir, "..", "..", "support", "android"))
sys.path.append(android_support_dir)

# We package markdown and simplejson in support/common.
common_support_dir = os.path.abspath(os.path.join(this_dir, "..", "..", "support", "common"))
sys.path.append(common_support_dir)
from markdown import markdown

from tilogger import *
log = None
all_annotated_apis = None

try:
	import json
except:
	import simplejson as json

def markdown_to_html(s):
	# When Ti Studio starts using a rich control for displaying code assist free text
	# (which they're planning, according to Kevin Lindsey), we can start doing more
	# with this like coming up with ways to link to other types.  For now the free-form
	# text goes straight is as html generated by markdown.  They strip out tags.
	# Discussed with Kevin 8/19/2011.
	html = markdown(s)
	# Any <Titanium.XX.XX> type of markdown links need to have their brackets removed so
	# the code assist doesn't see them as tags and thus strip them, thereby losing the
	# useful text within.  Same for known pseudo-types.
	pattern = r"\<[^\>\s]+\>"
	matches = re.findall(pattern, html)
	if matches:
		for m in matches:
			tag_name = m[1:-1]
			if tag_name.startswith("Titanium") or tag_name in all_annotated_apis:
				html = html.replace(m, tag_name)
	return html

# Fixes illegal names like "2DMatrix" (not valid Javascript name)
def clean_namespace(ns_in):
	def clean_part(part):
		if len(part) and part[0].isdigit():
			return "_" + part
		else:
			return part
	return ".".join([clean_part(s) for s in ns_in.split(".") ])

def build_deprecation_message(api):
	# Returns the message in markdown format.
	result = None
	if api.deprecated:
		result = "  **Deprecated"
		if api.deprecated.has_key("since"):
			result += " since %s." % api.deprecated["since"]
		if api.deprecated.has_key("removed"):
			result += " Removed in %s." % api.deprecated["removed"]
		if api.deprecated.has_key("notes"):
			result += " %s" % api.deprecated["notes"]
		result += "**"
	return result

def to_jsca_description(summary, api=None):
	if summary is None:
		return ""
	new_summary = summary
	if api is not None and api.deprecated is not None:
		deprecation_message = build_deprecation_message(api)
		if deprecation_message is not None:
			new_summary += deprecation_message
	return markdown_to_html(new_summary)

def to_jsca_example(example):
	return {
			"name": example["title"],
			"code": markdown_to_html(example["example"])
			}

def to_jsca_examples(api):
	if dict_has_non_empty_member(api.api_obj, "examples"):
		return [to_jsca_example(example) for example in api.api_obj["examples"]]
	else:
		return []

def to_jsca_type_name(type_info):
	if isinstance(type_info, list) or isinstance(type_info, tuple) and len(type_info) > 0:
		# Currently the JSCA spec allows for just one type per parameter/property/returnType.
		# We have to choose one.
		# We'll take "Object" if it's one of the possible types, else we'll just take the first one.
		if "object" in [t.lower() for t in type_info]:
			return "Object"
		else:
			return to_jsca_type_name(type_info[0])
	type_test = type_info
	if type_test.startswith("Callback"):
		type_test ="Function"