#!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
#
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at:
#
# http://joinup.ec.europa.eu/system/files/EN/EUPL%20v.1.1%20-%20Licence.pdf
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
#------------------------------------------------------------------------------

import socket
import sys
import pickle


def sendRequest(HOST, PORT, msg):
    """
    Send a msg to a WNoDeS TCP socket server.
    Msg format MUST BE a dictionary with one value-pair attribute.
    Key  MUST BE the method name you want to execute on the NameServer.
    Value MUST BE the options method weather they exist.
    If msg is not in this format an error is raised

    It returns a tuple with this format (status, data).
    """

    try:
        if len(msg.keys()) == 1:
            msg = str(pickle.dumps(msg).replace('\n', '1%2'))
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((HOST, int(PORT)))
                sock.sendall(msg + '\n')
                socketfile = sock.makefile('r', 0)
                response = socketfile.readline().strip()
                sock.shutdown(2)
                sock.close()
                try:
                    data = pickle.loads(response.replace('1%2', '\n'))
                    returnstuff = (0, data)
                    return returnstuff
                except pickle.UnpicklingError:

                    returnstuff = (1, None)
                    return returnstuff
                except Exception:

                    returnstuff = (1, None)
                    return returnstuff
            except socket.error:
                returnstuff = (1, None)
                return returnstuff
        else:
            returnstuff = (1, None)
            return returnstuff
    except:

        returnstuff = (1, '')
        return returnstuff

try:
    msg = {'stopProcess': ['all']}
    OUTPUT = sendRequest(sys.argv[1], 8222, msg)
except:
    sys.exit('CONNECTION ERROR. Maybe the process is not running')
