"""
This script gets the latest release notes from a specfied github repo, converts it from markdown to
reStructured Text format, and writes it to a text file.

The text file can be auto-imported by Sphinx into the official release notes.

----

The script uses the "Requests" module to make the API requests: http://docs.python-requests.org/en/latest/

Github API doc for getting latest release: https://developer.github.com/v3/repos/releases/#get-the-latest-release
    GET /repos/:owner/:repo/releases/latest

Where our release is: https://github.com/dronekit/dronekit-python/releases/tag/1.1.1
"""

import requests  # for making API requests
import re   # regular expressions to convert markup to reStructuredText
from optparse import OptionParser   # for command line options


def convert_markup_to_rst(text):
    """
    Convert mardown to rst format. Currently converts only (up to level 5) headings and links to rst format.
    """

    def fixheadings(matchobj):
        """
        Convert mardown headings to rst headings.
        """
        #print 'matched'
        #print matchobj.group(0)
        #print matchobj.group(1)
        #print matchobj.group(2)
        #print 'endmatched'
        heading_level=len(matchobj.group(1))
        heading_text=matchobj.group(2).strip()
        heading_length= len(heading_text)
        #print heading_level
        #print heading_text
        #print heading_length

        heading_char='='
        if heading_level == 1 :
            heading_char = '='
        if heading_level == 2 :
            heading_char = '-'
        if heading_level == 3 :
            heading_char = '~'
        if heading_level == 4 :
            heading_char = '+'
        if heading_level == 5 :
            heading_char = '*'
        heading_underline=heading_char*heading_length
        return heading_text+'\n'+heading_underline+'\n'


    def fixlinks(matchobj):
        """
        Convert mardown links to rst links.
        """
        #print 'matched'
        #print matchobj.group(0)
        #print matchobj.group(1)
        #print matchobj.group(2)
        #print 'endmatched'
        link_url=matchobj.group(2)
        link_text=matchobj.group(1)
        return '`%s <%s>`_' % (link_text,link_url)
        
    text=re.sub(r'^(\#+)\s+(.*)', fixheadings, text, flags=re.MULTILINE)
    text=re.sub(r'\[(.*?)\]\((.*?)\)', fixlinks, text, flags=re.MULTILINE) 
    
    return text



#parser options
parser = OptionParser(version="%prog 0.0.1", usage="Usage: %prog [options] version")
parser.add_option("-o", "--gitowner", dest="owner", default="diydrones", help="Owner of github repository")
parser.add_option("-r", "--repo", dest="repo", default="dronekit-python",help="Repo name")
parser.add_option("-f" , "--file", dest="file", default="./about/github_latest_release.txt",help="File path put output file")

(options, args) = parser.parse_args()

latest_release_url='https://api.github.com/repos/'+options.owner+'/'+options.repo+'/releases/latest'

print 'Fetching release notes: %s' % latest_release_url 

r = requests.get(latest_release_url)
bodytext_markdown=r.json()[u'body']
#print bodytext_markdown
print '  Converting markdown to reStructured text' 
bodytext_rst = convert_markup_to_rst(bodytext_markdown)

#Prefix with some documentation
bodytext_rst = ".. This document was auto-generated by the get_release_notes.py script using latest-release information from github \n\n" + bodytext_rst

#print "RST"
#print bodytext_rst
release_notes_file=open(options.file,'w')
release_notes_file.write(bodytext_rst)
release_notes_file.close()

print '  Complete' 

