#!/usr/bin/env python3
#
# Fake module for testing IRI message processing in IRI core
#
# Copyright (C) 2013 Radek Hranicky
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
import sys
import time
import os.path
import socket
import getopt
import string

sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))

from time import gmtime, strftime
from modules.sockets.li2 import connectUnixSocket
from modules.tools import signals
from modules.shared.nid import CreateNID
from modules.shared.nid import CreateNIDType
from modules.shared.nid import NIDIP

moduleName = "test"
socket = None

""" Sends a message to IRI core
"""
def sendMessage(msg):
    global socket
    msg += "\n"
    try:
        socket.send(msg.encode('utf-8'))
    except:
        print("Sending the message through socket failed!")
        return
    print("Message sent to IRI core.")


""" Computes current unix time with miliseconds

    Returns unix time
    """
def time_nowF():
    unixTime = str(time.time())
    parts = unixTime.split('.')
    if len(parts[1]) == 1:
        parts[1] = parts[1] + "0"
    return float(str(int(time.mktime(time.localtime()))) + "." + parts[1])


""" Generates a new IRI message

    moduleName Name of the IRI-IIF module
    iriType Type of IRI message (BEGIN/CONTINUE/END)
    description Description of event
    nidset Set of NIDs which will be included into the message
    
    Returns generated IRI message as a string
    """    
def generateIRIMessage(moduleName, iriType, description, nidset):
    nids_str = "["
    nidcount = len(nidset)
    nidnum = 0
    for nid in nidset:
        nidnum += 1
        nids_str += "('"
        nids_str += nid.getType()
        if nid.getType() == "TCP" or nid.getType == "E-mail message":
            nids_str += "',"
        else:
            nids_str += "','"
        nids_str += str(nid.getValue())
        if nid.getType() == "TCP" or nid.getType == "E-mail message":
            nids_str += ")"
        else:
            nids_str += "')"
        if (nidnum < nidcount):
            nids_str += ", "
    nids_str += "]"
    return "('"+moduleName+"', "+str(time_nowF())+", '"+iriType+"', '"+description+"', "+nids_str+")"


""" Main loop for interaction with user
    """
def mainLoop():
    global moduleName
    print("Fake IRI-IIF module - Connected to IRI-CORE.")
    moduleName = input('module name [test]: ')
    if moduleName == "":
        moduleName = "test"
    nextMessage = True
    print()
    while nextMessage:
        print("New IRI message...")
        iriType = input('IRI type [BEGIN]: ')
        if iriType == "":
            iriType = "BEGIN"
        description = input('Description [Just testing.]: ')
        if description == "":
            description = "Just testing."
        nids = set()
        nidval = "."
        while True:
            print()
            print("Create a new NID or press ENTER twice to finish...")
            nidtype = input('NID type [auto detect]: ')
            
            if nidtype=="TCP":
                # Support for TCP
                c_ip = input('TCP client IP: ')
                c_port = input('TCP client port: ')
                s_ip = input('TCP server IP: ')
                s_port = input('TCP server port: ')
                nidval = (str(c_ip), int(c_port), str(s_ip), int(s_port))
            else:
                nidval = input('NID value: ')
            
            if nidval == "":
                break
            if nidtype == "":
                try:
                    nid = CreateNID(nidval)
                except:
                    print("Automatic detection of NID type failed. Try again!")
                    continue
            else:
                try:
                    nid = CreateNIDType(nidval, nidtype)
                except:
                    print("Unable to create NID type ", nidtype, " from ", nidval, ". Try again!")
                    continue
            nids.add(nid)
        msg = generateIRIMessage(moduleName, iriType, description, nids)
        print()
        print("Message:")
        print(msg)
        snd = input('Send to IRI core (y/n)? [y]: ')
        if snd == "y" or snd == "Y" or snd == "":
            sendMessage(msg)
        print()
        nxt = input('Create another message (y/n)? [y]: ')
        if nxt == "n" or nxt == "N":
            nextMessage = False

def main(argv):
    global db
    global socket
    global debugMode
    global mode
    
    if os.geteuid() != 0:
        sys.stderr.write("You must be root to run this script.\n")
        exit()
    
    try:
        socket = connectUnixSocket("/tmp/iricol")
    except:
        print("Unable to connect to IRI core.")
        return
    
    mainLoop()
    

if __name__ == "__main__":
    try:
        main(sys.argv)
    except Exception as e:
        print("Terminated on exception: ", e)
