#!/usr/bin/python

import argparse
import sys

sys.path.append("src")

from clixxIO  import *

parser = argparse.ArgumentParser(description='Command Line Device Interface.')

useage = """
clixx.io Command Line
---------------------

clixx.io with command line interface to monitor
sensors. 

 clixx.io --latest log Temp1      # Display the log
 clixx.io info Temp1              # Info about the sensor
 cixx.io disconnect Temp1         # Safely disconnect the device
 clixx.io connect Temp1

 clixx.io list                    # List all devices
 
 clixx.io brandname "Scrooge Engineering"
 
 clixx.io webserver start
 clixx.io webserver stop

 clixx.io add button pin/gpio X
 clixx.io add led d1
 clixx.io rm Temp1
 clixx.io start Temp1
 clixx.io stop Temp1
 
"""

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('operation', nargs='+', help="Perform an operation on a device [add/remove/activate/deactive/list/history/status]")

    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
   
    args = parser.parse_args()
    
    if args.operation[0]=="list":
        
        if len(args.operation)==1:
            print("Current Projects\nName--------------------- Type------------------------ Status------------------")
            projects = clixxIOListProjects()
            types = clixxIOListProjectbyType()
            statuses = clixxIOListProjectbyStatus()
            
            for p in projects:
                print("%s %s %s" % ('{:25}'.format(p),'{:<26}'.format(types[p]),'{:<26}'.format(statuses[p])))
                
        else:
            if args.operation[1]=="autostarts":
                autostarts = clixxIOProjectAutostarts()
                print autostarts
                sys.exit(0)

            if args.operation[1]=="input_channels":
                projname = args.operation[2]
                print(clixxIOListProjectMqttSubs(projname))
                sys.exit(0)

            elif args.operation[1]=="output_channels":
                projname = args.operation[2]
                print(clixxIOListProjectMqttPubs(projname))
                sys.exit(0)

            elif args.operation[1]=="commands":
                projname = args.operation[2]
                print(clixxIOListProjectMqttCommands(projname))
                sys.exit(0)
                
            else:
                print("Command error \"%s\" not understood" % args.operation[1])
                sys.exit(0)

    elif args.operation[0]=="pubs":
        
        projname = args.operation[1]
        projects = clixxIOListProjects()
        
        if projname in projects:
            print(clixxIOListProjectMqttPubs(projname))
        else:
            print("%s  is not a valid project" % projname)
            sys.exit(1)

    elif args.operation[0]=="subs":
        
        projname = args.operation[1]
        projects = clixxIOListProjects()
        
        if projname in projects:
            print(clixxIOListProjectMqttSubs(projname))
        else:
            print("%s  is not a valid project" % projname)
            sys.exit(1)
            
    elif args.operation[0]=="commands":
        projname = args.operation[1]
        print(clixxIOListProjectMqttCommands(projname))
        sys.exit(0)
            
    elif args.operation[0]=="add":

        if args.operation[1]=="sub":
            # Add a new project
            projname = args.operation[2]
            clixxIO.clixxIOAddProjectMqttSub(projname,args.operation[3])
            sys.exit(0)
            
        if args.operation[1]=="pub":
            # Add a new project
            projname = args.operation[2]
            clixxIOAddProjectMqttPub(projname, args.operation[3])
            sys.exit(0)
            
        if args.operation[1]=="command":
            # Add a new project
            projname = args.operation[2]
            clixxIO.clixxIOAddProjectMqttCommands(projname,args.operation[3])

    elif args.operation[0]=="new":

        if args.operation[1]=="project":
            # Add a new project
            projname = args.operation[2]
            print("Creating new project %s" % projname)
            sys.exit(clixxIOAddProject(args.operation[2]))
            
    elif args.operation[0]=="remove":

        if args.operation[1]=="project":
            # Add a new project
            projname = args.operation[2]
            sys.exit(clixxIORemoveProject(projname))
        else:
            print("Invalid parameter")
            
    elif args.operation[0]=="show":
        
        if args.operation[1]=="config":
            
            # Show the location of the configuratino
            print("Configuration file location is set to %s" % configPath())
            
            if (os.path.exists(configPath())):
                
                pass
                
            else:
                
                print("Configuration file %s doesn't exist." % configPath())
            
            sys.exit(0)
            
        else:
            print("Invalid parameter")

    elif args.operation[0]=='history':
        print(clixxIOLatestValues(args.device[1]))
    elif args.operation[0]=="status":
        print(clixxIOReadDevice(args.device[1]))
    elif args.operation[0]=='watch':
        pass
    else:
        print("Unknown command.")
