#!/usr/bin/env python
from __future__ import unicode_literals
import web
from sys import argv
from urllib import urlencode
from secure_connection import SecureConnection
import config

def send_update(job_id, status, message):
    '''
    Sends an update to the server daemon about a job being done
    '''
    print  "send_update", status, message
    connection = SecureConnection(config.server_daemon_ip, config.server_daemon_port)
    try:
        url = '/updatejob/%s/%s' % (job_id, status)
        post_data = urlencode({'message': message})
        headers = {"Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"}
        connection.request('POST', url, post_data, headers)
        response = connection.getresponse()
        response_data = response.read()
        print config.server_daemon_ip, config.server_daemon_port, url, "response.status", response.status, response_data
    except SocketError, e:
        print "SocketError", e.__str__()
    except SSLError, e:
        print "SSLError", e.__str__()
    connection.close()

#def send_job(job_id, request):
    #connection = SecureConnection(config.client_daemon_ip, config.client_daemon_port)
    #url = '/jobrequest/%s' % job_id
    #post_data = urlencode({'request': request})
    #headers = {"Content-type": "application/x-www-form-urlencoded",
        #"Accept": "text/plain"}
    #connection.request('POST', url, post_data, headers)
    #response = connection.getresponse()
    #print config.client_daemon_ip, config.client_daemon_port
    #print response.status, response.read()

if __name__ == "__main__":
    if argv.__len__() != 4:
        print "Usage: %s <job_id> <status> <message>" % argv[0]
    else:
        send_update(argv[1], argv[2], argv[3])
