#!/usr/bin/env python3
# HI1 interface controller
# Copyright (C) 2011 Matěj Grégr, Michal Kajan, Libor Polčák, Vladimír Veselý
# 
# 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
from modules.af.hi1intercept import HI1Intercept
from modules.sockets.li import tcpSocketAsClient
from modules.tools.config import parseServerTcpIfcConfig
import modules.tools.log as log

def printHelp(func):
    """ Prints help using given function """
    func("Usage of insert.py:")
    func("Add new interception")
    func("./insert.py LIID NID LEVEL(1-3) start_time end_time")
    func("start/end time - day.month.year. day.month.year hour:min")
    func("Remove existing interception")
    func("./insert.py -d LIID")

def main(argv):
    log.setupLogging(argv[1:])
    if len(argv) == 2 and argv[1] in ["-h", "--help"]:
        printHelp(print)
    else:
        if "-d" in argv:
            checkArgNumber(3, argv)
            action = "delete_intercept"
            argv = [arg for arg in argv if arg != "-d"]
            i = argv[1]
        else:
            checkArgNumber(6, argv)
            action = "new_intercept"
            i = HI1Intercept(*argv[1:])
        # Prepare interfaces
        server, port = parseServerTcpIfcConfig("hi1", "af.ini")
        hi1 = tcpSocketAsClient("hi1", server, port)
        hi1.send((action, i))
        r = hi1.receive()
        hi1.close()
        if r[0] == "ack":
            log.debug(r)
        else:
            log.critical(r[0])
            sys.exit(1)

def checkArgNumber(expectedNum, argv):
    if len(argv) != expectedNum:
        sys.stderr.write("Unknown number of arguments\n")
        printHelp(lambda s: sys.stderr.write(s + "\n"))
        sys.exit(1)

if __name__ == "__main__":
    try:
        main(sys.argv)
    except Exception as e:
        sys.stderr.write(str(e))
        sys.exit(1)

