#!/usr/bin/python

"""
Look up airport codes.

WARNING: Do not use this module for any commercial purposes.  This
module is not approved for use by world-airport-codes.com nor is there
any association between the site and the developer of this module.

Example:

    >>> airportcodes.byCode('JFK')
    ('United States', 'John F. Kennedy International')
    >>> airportcodes.byString('Toronto')
    (u'Canada', u'Lester B. Pearson International')


"""
from __future__ import unicode_literals

__author__  = 'Michael Stella <airportcodes@thismetalsky.org>'
__license__ = 'Apache 2.0'
__version__ = '0.1'

import re, sys
import mechanize
try:
    from ClientForm import ItemNotFoundError
except:
    from mechanize import ItemNotFoundError

def byCode(code):
    return _lookup(code, 'airportcode')

def byName(name):
    return _lookup(name, 'airportname')


def _lookup(value, option):

    # here's our "browser"
    br = mechanize.Browser()
    br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

    # get the first page
    rsp = br.open('http://www.world-airport-codes.com')

    # fill out form
    br.select_form(nr=0)
    try:
        br.form.set_value(value,    name=b'criteria')
        br.form.set_value([option], name=b'searchWhat')
    except ItemNotFoundError, e:
        raise

    rsp = br.submit()

    url = rsp.geturl()

    m = re.match('http://www.world-airport-codes.com/([^/]+)/(.+?)-\d+\.html', url)
    if m:
        country = ' '.join(list(w.capitalize() for w in m.group(1).split('-')))
        airport = ' '.join(list(w.capitalize() for w in m.group(2).split('-')))

        # If searching by code, there's only one result.
        if option == 'airportcode':
            return (value.upper(), country, airport)

        # if we're searching by name, we must fetch the airport code too
        elif option == 'airportname':
            result = rsp.read()
            m2 = re.search('<label class="detail">Airport Code</label>\s*<span class="detail">: ([^<]+)</span>', result)
            if m2:
                return (m2.group(1), country, airport)

            # oops, didn't find it
            return (None, country, airport)


if __name__ == '__main__':
    print _lookup(*sys.argv[1:3])


"""
Copyright 2011 Michael Stella

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""


