import config
from state.server import Server
from state.changer import Changer
from state.file import File
import commands

def safely_panic():
    safe_state = {}
    changer = Changer(safe_state,safe_state)
    changer.stop_everything()

def reboot_if_network_down():
    try:
        server = Server(config.API_BASE_URL, config.CONTROLLER_ID)
        server_state = server.get_state()
        print "Got state from server: " + repr(server_state)
    except:
        print "Problem with the network!"
        commands.getoutput('/sbin/shutdown -r +3')

def sync():
    try:
        server = Server(config.API_BASE_URL, config.CONTROLLER_ID)
        local = File(config.STATE_FILE)
        server_state = server.get_state()

        if local.present():
            local.load()
            print "local present: " + repr(local.data)
        else:
            local.data = server_state
            print "local not present, server: " + repr(local.data)
            local.save()

        local_state = local.data

        changer = Changer(local_state, server_state)
        current_state = changer.process_change()

        print "posting :" + repr(current_state)
        local.data = current_state
        server.post_state(current_state)
        local.save()
    except:
        print " panicking safely ! "
        safely_panic()
