#!/usr/bin/python
from lib import ciplaces
from lib import ciutils
from lib import ciconf
import logging

IS_DEBUG = False

def init():
    global IS_DEBUG

    if IS_DEBUG:
        log_level = logging.DEBUG
        log_file = None
    else:
        log_level = logging.INFO
        log_file = ciconf.LOG_FILE

    # NOTE: to enable module/method tracking: add '[%(module)s.%(funcName)s]'
    logging.basicConfig(filename=log_file, level=log_level, datefmt='%Y.%m.%d %H:%M:%S', 
                        format='%(asctime)s [%(levelname)s]\t%(message)s')

def load_last_ap():
    latest_ap = ''
    try:
        config = open(ciconf.LATEST_AP, 'r')
        latest_ap = config.read()
        config.close()
    except Exception, ex:
        logging.error('Failed to load last AP: %s' % str(ex))
    return latest_ap

def update_last_ap(latest_ap):
    logging.debug('Updating latest AP: %s' % latest_ap)
    config = open(ciconf.LATEST_AP, 'w')
    config.write(latest_ap)
    config.close()

def go():
    location_list = ciplaces.get_instance().get_place_list()

    last_ap = load_last_ap()
    current_ap = ciutils.get_ap_name()

    if not current_ap:
        logging.info('No connection...bye.')
        return 0
    elif last_ap == current_ap:
        logging.info('I am not connecting to different AP...bye :)')
    else:
        i_know_this_place = False
        logging.info('Changing AP from [%s] to [%s].' % (last_ap, current_ap))
        for location in location_list.keys():
            if current_ap in location_list[location].ap_name:
                location_list[location].i_am_here()
                i_know_this_place = True
            elif last_ap in location_list[location].ap_name:
                location_list[location].leaving_here()
        if not i_know_this_place:
            logging.warning('Current AP is not recorded.')

    update_last_ap(current_ap)
    logging.info('Currently connecting to AP [%s] with IP [%s]' % (current_ap, ciutils.get_current_ip()))
    return 0

if __name__ == '__main__':
    init()
    go()
@@ -984,16 +984,342 @@
 lose()%0A%0A
+def show_notification(current_ap, ip):%0A    from commands import getstatusoutput%0A    cmd = '/usr/local/bin/terminal-notifier -title %5C%22Check In%5C%22 -message %5C%22just checked in at:%5Cn%25s (%25s)%5C%22 -contentImage %5C%22/Users/reverb/Dropbox/Photos/icon/Reverb/Reverb by Dannvix.png%5C%22' %25 (current_ap, ip)%0A    (ret, out) = getstatusoutput(cmd)%0A%0A
 def go()
@@ -1316,24 +1316,24 @@
 %0A%0Adef go():%0A
-
     location
@@ -1535,16 +1535,151 @@
 return 0
+%0A%0A    ip = ciutils.get_current_ip()%0A    if ip == '127.0.0.1':%0A        logging.info('No IP assigned. Keep sleeping...')%0A        return 0
 %0A    eli
@@ -1895,16 +1895,58 @@
 nt_ap))%0A
+        show_notification(current_ap, ip)%0A
         
@@ -2462,32 +2462,10 @@
 ap, 
-ciutils.get_current_ip()
+ip
 ))%0A 

add notification support (requires terminal-notifier)