#!/usr/bin/env python
# -*- coding: utf-8 -*-

names = { "ATA": "Antarctica", "AFG":"Afghanistan", "ALA":"Åland Islands", "ALB":"Albania", "DZA":"Algeria", 
          "ASM":"American Samoa", "AND":"Andorra", "AGO":"Angola", "AIA":"Anguilla", "ATG":"Antigua and Barbuda", 
          "ARG":"Argentina", "ARM":"Armenia", "ABW":"Aruba", "AUS":"Australia", "AUT":"Austria", "AZE":"Azerbaijan",
          "BHS":"Bahamas", "BHR":"Bahrain", "BGD":"Bangladesh", "BRB":"Barbados", "BLR":"Belarus", "BEL":"Belgium",
          "BLZ":"Belize", "BEN":"Benin", "BMU":"Bermuda", "BTN":"Bhutan", "BOL":"Bolivia (Plurinational State of)",
          "BES":"Bonaire, Sint Eustatius and Saba", "BIH":"Bosnia and Herzegovina", "BWA":"Botswana",
          "BVT":"Bouvet Island", "BRA":"Brazil", "IOT":"British Indian Ocean Territory", "VGB":"British Virgin Islands",
          "BRN":"Brunei Darussalam", "BGR":"Bulgaria", "BFA":"Burkina Faso", "BDI":"Burundi", "CPV":"Cabo Verde",
          "KHM":"Cambodia", "CMR":"Cameroon", "CAN":"Canada", "CYM":"Cayman Islands", "CAF":"Central African Republic",
          "TCD":"Chad", "CHL":"Chile", "CHN":"China", "HKG":"China, Hong Kong Special Administrative Region",
          "MAC":"China, Macao Special Administrative Region", "CXR":"Christmas Island", "CCK":"Cocos (Keeling) Islands",
          "COL":"Colombia", "COM":"Comoros", "COG":"Congo", "COK":"Cook Islands", "CRI":"Costa Rica",
          "CIV":"Côte d'Ivoire", "HRV":"Croatia", "CUB":"Cuba", "CUW":"Curaçao", "CYP":"Cyprus", "CZE":"Czechia",
          "PRK":"Democratic People's Republic of Korea", "COD":"Democratic Republic of the Congo", "DNK":"Denmark",
          "DJI":"Djibouti", "DMA":"Dominica", "DOM":"Dominican Republic", "ECU":"Ecuador", "EGY":"Egypt",
          "SLV":"El Salvador", "GNQ":"Equatorial Guinea", "ERI":"Eritrea", "EST":"Estonia", "ETH":"Ethiopia",
          "FLK":"Falkland Islands (Malvinas)", "FRO":"Faroe Islands", "FJI":"Fiji", "FIN":"Finland", "FRA":"France",
          "GUF":"French Guiana", "PYF":"French Polynesia", "ATF":"French Southern and Antarctic Territories",
          "GAB":"Gabon", "GMB":"Gambia", "GEO":"Georgia", "DEU":"Germany", "GHA":"Ghana", "GIB":"Gibraltar",
          "GRC":"Greece", "GRL":"Greenland", "GRD":"Grenada", "GLP":"Guadeloupe", "GUM":"Guam", "GTM":"Guatemala",
          "GGY":"Guernsey", "GIN":"Guinea", "GNB":"Guinea-Bissau", "GUY":"Guyana", "HTI":"Haiti",
          "HMD":"Heard Island and McDonald Islands", "VAT":"Holy See", "HND":"Honduras", "HUN":"Hungary",
          "ISL":"Iceland", "IND":"India", "IDN":"Indonesia", "IRN":"Iran (Islamic Republic of)", "IRQ":"Iraq",
          "IRL":"Ireland", "IMN":"Isle of Man", "ISR":"Israel", "ITA":"Italy", "JAM":"Jamaica", "JPN":"Japan",
          "JEY":"Jersey", "JOR":"Jordan", "KAZ":"Kazakhstan", "KEN":"Kenya", "KIR":"Kiribati", "KWT":"Kuwait",
          "KGZ":"Kyrgyzstan", "LAO":"Lao People's Democratic Republic", "LVA":"Latvia", "LBN":"Lebanon", "LSO":"Lesotho",
          "LBR":"Liberia", "LBY":"Libya", "LIE":"Liechtenstein", "LTU":"Lithuania", "LUX":"Luxembourg",
          "MDG":"Madagascar", "MWI":"Malawi", "MYS":"Malaysia", "MDV":"Maldives", "MLI":"Mali", "MLT":"Malta",
          "MHL":"Marshall Islands", "MTQ":"Martinique", "MRT":"Mauritania", "MUS":"Mauritius", "MYT":"Mayotte",
          "MEX":"Mexico", "FSM":"Micronesia (Federated States of)", "MCO":"Monaco", "MNG":"Mongolia", "MNE":"Montenegro",
          "MSR":"Montserrat", "MAR":"Morocco", "MOZ":"Mozambique", "MMR":"Myanmar", "NAM":"Namibia", "NRU":"Nauru",
          "NPL":"Nepal", "NLD":"Netherlands", "NCL":"New Caledonia", "NZL":"New Zealand", "NIC":"Nicaragua",
          "NER":"Niger", "NGA":"Nigeria", "NIU":"Niue", "NFK":"Norfolk Island", "MNP":"Northern Mariana Islands",
          "NOR":"Norway", "OMN":"Oman", "PAK":"Pakistan", "PLW":"Palau", "PAN":"Panama", "PNG":"Papua New Guinea",
          "PRY":"Paraguay", "PER":"Peru", "PHL":"Philippines", "PCN":"Pitcairn", "POL":"Poland", "PRT":"Portugal",
          "PRI":"Puerto Rico", "QAT":"Qatar", "KOR":"Republic of Korea", "MDA":"Republic of Moldova", "REU":"Réunion",
          "ROU":"Romania", "RUS":"Russian Federation", "RWA":"Rwanda", "BLM":"Saint Barthélemy", "SHN":"Saint Helena",
          "KNA":"Saint Kitts and Nevis", "LCA":"Saint Lucia", "MAF":"Saint Martin (French Part)",
          "SPM":"Saint Pierre and Miquelon", "VCT":"Saint Vincent and the Grenadines", "WSM":"Samoa", "SMR":"San Marino",
          "STP":"Sao Tome and Principe", "SAU":"Saudi Arabia", "SEN":"Senegal", "SRB":"Serbia", "SYC":"Seychelles",
          "SLE":"Sierra Leone", "SGP":"Singapore", "SXM":"Sint Maarten (Dutch part)", "SVK":"Slovakia", "SVN":"Slovenia",
          "SLB":"Solomon Islands", "SOM":"Somalia", "ZAF":"South Africa",
          "SGS":"South Georgia and the South Sandwich Islands", "SSD":"South Sudan", "ESP":"Spain", "LKA":"Sri Lanka",
          "PSE":"State of Palestine", "SDN":"Sudan", "SUR":"Suriname", "SJM":"Svalbard and Jan Mayen Islands",
          "SWZ":"Swaziland", "SWE":"Sweden", "CHE":"Switzerland", "SYR":"Syrian Arab Republic", "TJK":"Tajikistan",
          "THA":"Thailand", "MKD":"The former Yugoslav Republic of Macedonia", "TLS":"Timor-Leste", "TGO":"Togo",
          "TKL":"Tokelau", "TON":"Tonga", "TTO":"Trinidad and Tobago", "TUN":"Tunisia", "TUR":"Turkey",
          "TKM":"Turkmenistan", "TCA":"Turks and Caicos Islands", "TUV":"Tuvalu", "TWN":"Taiwan", "UGA":"Uganda",
          "UKR":"Ukraine", "ARE":"United Arab Emirates", "GBR":"United Kingdom of Great Britain and Northern Ireland",
          "TZA":"United Republic of Tanzania", "UMI":"United States Minor Outlying Islands",
          "USA":"United States of America", "VIR":"United States Virgin Islands", "URY":"Uruguay",
          "UZB":"Uzbekistan", "VUT":"Vanuatu", "VEN":"Venezuela (Bolivarian Republic of)", "VNM":"Viet Nam",
          "WLF":"Wallis and Futuna Islands", "ESH":"Western Sahara", "YEM":"Yemen", "ZMB":"Zambia", "ZWE":"Zimbabwe",
          "N":"No countries visited" }
 
places = [ 'ABW','AFG','AGO','AIA','ALA','ALB','AND','ARE','ARG','ARM',
           'ASM','ATA','ATF','ATG','AUS','AUT','AZE','BDI','BEL','BEN',
           'BES','BFA','BGD','BGR','BHR','BHS','BIH','BLM','BLR','BLZ',
           'BMU','BOL','BRA','BRB','BRN','BTN','BVT','BWA','CAF','CAN',
           'CCK','CHE','CHL','CHN','CIV','CMR','COD','COG','COK','COL',
           'COM','CPV','CRI','CUB','CUW','CXR','CYM','CYP','CZE','DEU',
           'DJI','DMA','DNK','DOM','DZA','ECU','EGY','ERI','ESH','ESP',
           'EST','ETH','FIN','FJI','FLK','FRA','FRO','FSM','GAB','GBR',
           'GEO','GGY','GHA','GIB','GIN','GLP','GMB','GNB','GNQ','GRC',
           'GRD','GRL','GTM','GUF','GUM','GUY','HKG','HMD','HND','HRV',
           'HTI','HUN','IDN','IMN','IND','IOT','IRL','IRN','IRQ','ISL',
           'ISR','ITA','JAM','JEY','JOR','JPN','KAZ','KEN','KGZ','KHM',
           'KIR','KNA','KOR','KWT','LAO','LBN','LBR','LBY','LCA','LIE',
           'LKA','LSO','LTU','LUX','LVA','MAC','MAF','MAR','MCO','MDA',
           'MDG','MDV','MEX','MHL','MKD','MLI','MLT','MMR','MNE','MNG',
           'MNP','MOZ','MRT','MSR','MTQ','MUS','MWI','MYS','MYT','NAM',
           'NCL','NER','NFK','NGA','NIC','NIU','NLD','NOR','NPL','NRU',
           'NZL','OMN','PAK','PAN','PCN','PER','PHL','PLW','PNG','POL',
           'PRI','PRK','PRT','PRY','PSE','PYF','QAT','REU','ROU','RUS',
           'RWA','SAU','SDN','SEN','SGP','SGS','SHN','SJM','SLB','SLE',
           'SLV','SMR','SOM','SPM','SRB','SSD','STP','SUR','SVK','SVN',
           'SWE','SWZ','SXM','SYC','SYR','TCA','TCD','TGO','THA','TJK',
           'TKL','TKM','TLS','TON','TTO','TUN','TUR','TUV','TWN','TZA',
           'UGA','UKR','UMI','URY','USA','UZB','VAT','VCT','VEN','VGB',
           'VIR','VNM','VUT','WLF','WSM','YEM','ZAF','ZMB','ZWE','N' ]

def printlist():
    for place in places:
        print("%-3s - %s" % (place, names[place]))
 
def base36encode(integer):
    chars, encoded = '0123456789abcdefghijklmnopqrstuvwxyz', ''
    while integer > 0:
        integer, remainder = divmod(integer, 36)
        encoded = chars[remainder] + encoded
    return encoded
 
def makeurl(i_visited):
    my_whacky_array = []
    my_whacky_string = '0b1'
    
    for index in xrange(len(places)):
        my_whacky_string += '1' if places[index] in i_visited else '0'
        if index and not index%50:
            my_whacky_array.append(base36encode(eval(my_whacky_string)))
            my_whacky_string = '0b1'
    my_whacky_array.append(base36encode(eval(my_whacky_string)))
    return("http://map1.maploco.com/visited-countries/mine.php?c1="+'-'.join(my_whacky_array))

def show_suggestions(searchstring):
    suggestions = {}
    for code in places:
        if searchstring.lower() in names[code].lower():
            suggestions[code] = names[code]
    if len(suggestions)>1:
        print("\nDid you mean:")
        for code, place in suggestions.iteritems():
            print("%-60s  Type: %s" % (place+"?", code))
    elif len(suggestions)==1:
        return(suggestions.keys()[0])
    else:
        print("\x1b[31;1mSorry, I couldn't find any matches for that search!\x1b[0m")

def interact():
    visited_countries = []
    print("What countries have you visited?  Type the 3-letter ISO 3166-1 code, if you know it; a partial search string;\nor press enter to see a complete list:")
    choice = raw_input(": ")
    while choice != 'Q' and choice != 'q':
        if len(choice)==0: 
            printlist()
        elif len(choice)==3 and choice.upper() in places:
           visited_countries.append(choice.upper())
        else:
            lookup=show_suggestions(choice)
            if lookup:
                visited_countries.append(lookup)
        if len(visited_countries):
            visited_names = []
            for country in visited_countries:
                visited_names.append(names[country])
            print("\nCountries added so far: \x1b[32;1m" + ', '.join(visited_names) + "\x1b[0m")
            print("View your map at:\n\x1b[34;1m" + makeurl(visited_countries) + "\x1b[0m")
            print("\nWould you like to add more?  Type the 3-letter ISO 3166-1 code, if you know it; a partial search string;\nor press enter to see a complete list -- otherwise type 'Q' to quit:")
        choice = raw_input(": ")

if __name__ == "__main__":
    interact()