#!/usr/bin/env python3

from fire import Fire
#from tdb_io import mongo
from tdb_io.version import __version__

from tdb_io import mongo
from tdb_io import influx
from tdb_io import h5toinfl

# plotting like in earlier mymongo
from tdb_io import h5t

# new thing - import org emacs table - 1 per file now
from tdb_io import org2h5

import os

import socket

def launch(MODE="help", *args, **kwargs):
#==============================================
    if MODE=="help":
        print("h... available modes: \n\t\t usage |  insert | ls | chk infl")
        print("\t\t... usage      \t Show usage examples.. ")
        print("\t\t... ls      \t This lists influxdb OR h5 file")
        print("\t\t... insert  \t This inserts into MONGO and INFLUXDB")
        print("\t\t... chk infl \t REMOVES&CREATES local influx db I_AM_*")
        print("\t\t...          \t allow for looking at hostname remotely")
        print("\t\t... plt filename.h5  -p c  -l  -w    \t plot c vs. t[ime] graph (nolines,show)")
        quit()
    print("D... args  = ", args)
    print("D... kwargs= ", kwargs)

    if MODE=="usage":
        print("USAGE:")
        print("\t... ls      \t  ls infl")
        print("\t...         \t  ls infl test")
        print("\t...         \t  ls infl -ip 192.168.0.19")
        print("\t...         \t  ls infl test zen")
        print("\t...         \t  ls infl test zen --delete ?")
        print("\t...         \t  ... to delete measurement ?")
        print()
        print("\t...         \t  ls ../mymongo/manual_mongo2h5/data_home_electro.h5")
        print("\t...         \t  ls home_electro_20201221_142425.h5 ")
        print("\t...         \t  ls home_electro_20201221_142425.h5 /T20201221_142425")
        print()
        print("\t... plt    \t  plt home_electro_20201221_151030.h5 -p low -w")
        print("\t...        \t  plt home_electro_20201221_151030.h5 -p low -w a.jpg")
        print("\t...        \t  plt home_electro_20201221_151030.h5 -p low -w a.txt")
        print("\t...        \t  plt home_electro_20201221_151030.h5 -p low -w a.org???")
        print("\t... plt derivative")
        print("\t...        \t  plt home_electro_20201221_151030.h5 -p d_low -D 1y -w ")
        print("\t...        \t  plt home_electro_20201221_151030.h5 -p d_low -D 1y -l 18m -w")
        print("\t... plt derivative 2axes")
        print("\t...        \t  plt home_electro_20201221_151030.h5 -p low:d_low -D 1y -w ")
        print()
        print('\t... insert  \t  insert -v "aas:dsa,we:sdf" ??? ')
        print("\t... chk infl \t  chk infl")
        quit()
    #print("D... args  = ", args)
    #print("D... kwargs= ", kwargs)

    print("D... MODE=",MODE)
#==============================================
    if MODE=="insert":
        if len(args)==0:
            print("H... ./"+os.path.basename(__file__)+" insert database collection/measurementname -v a=1,b=2 ")
            quit()
        database=args[0]
        collection=args[1]
        values=kwargs['v']
        mongo.mongowrite( database, collection, values ) # writes influx too
        influx.influxwrite( database, collection, values )
#==============================================

    if MODE=="ls":

        if len(args)==0:
            print("H... ./"+os.path.basename(__file__)+"  filename.h5 ")
            quit()
        #print("ok")
        if args[0].find(".h5")>0:
            fvalue = False
            if 'f' in kwargs:
                fvalue=kwargs['f'] # full text
            print("D... fval/kwargs",fvalue, kwargs)
            print("D... args",args)
            if len(args)==1:
                h5toinfl.read_h5( args[0], fulltext=fvalue )
            else: # key also
                h5toinfl.read_h5( args[0], key=args[1], fulltext=fvalue )

        #================ influx
        elif (args[0]=="infl")or(args[0]=="influx"):
            print("D...  listing influx databases")
            dbcheck = "_"
            sercheck = ""
            qlimit = 10
            IP = "127.0.0.1"
            delete = False
            dbpr = False
            if len(args)>1:
                dbcheck = args[1]
                print("D... args  = ",args)
                print("D... kwargs=",kwargs)
            if len(args)>2:
                sercheck = args[2]
            if len(args)>3:
                qlimit = args[3]
            if len(args)>4:
                IP = args[4]
            if len(kwargs)>0:
                if 'delete' in kwargs.keys():
                    delete = kwargs["delete"]
                if 'ip' in kwargs.keys():
                    IP = kwargs["ip"]
                    print(f"D... IP == {IP}")

            res = influx.check_databases(IP=IP)
            print("D... done")
            for i in res:
                if i['name'].find("_")==0:
                    continue
                chk = " "
                if dbcheck == i["name"]:
                    chk = "*"
                    dbpr = True
                print( chk, i["name"] )

            if dbpr:
                res = influx.check_series(dbcheck) #check 1 database

                if sercheck in res:
                    influx.check_series(dbcheck, sercheck, qlimit, IP) #check 1 series
                    if delete:
                        influx.check_series(dbcheck, sercheck, delete=True)
        #rlwrap influx -precision rfc3339
        # show databases
        # use test
        # show measurements


    if MODE=="chk":
        if len(args)==0:
            print("H... ./"+os.path.basename(__file__)+" chk  infl ")
            quit()
        #================ influx
        if (args[0]=="infl")or(args[0]=="influx"):
                influx.checkout_hostname_database()

    if MODE=="print":
        if len(args)==0:
            print("H... ./___  filename.h5 [item]")
            quit()
        print("ok")
        h5toinfl.read_h5( args[0] )


    if MODE=="plt":
        print("D... plot with h5t.py: ", args)
        print("D... tdb_io plt  reference_repo.h5  -p temp  ")
        print("D... tdb_io plt  reference_repo.h5  -p size,size  ")
        pvalue = ""
        wvalue = False
        Dvalue="" # default

        newkwargs={}  # new keyWARGS
        if 'p' in kwargs: newkwargs['plot']=kwargs['p']
        if 'w' in kwargs: newkwargs['writejpg']=kwargs['w']
        if 'D' in kwargs: newkwargs['DERIVATIVE']=kwargs['D']
        if 'l' in kwargs: newkwargs['lines_off']=kwargs['l']
         # #values="",
         # DERIVATIVE="",
         # INTEGRAL=False,
         # last="",
         # background="white",
         # points_off=False,
         # lines_off=False,
         # writejpg=False,

        # if 'p' in kwargs:
        #     pvalue=str(kwargs['p']) # plot
        # if 'w' in kwargs:
        #     wvalue = kwargs['w'] # write
        # if "D" in kwargs:
        #     Dvalue = kwargs['D']

        # ---- newkwargs - send all
        if len(args)==1: # FILENAME
            #h5t.main(args[0], plot = pvalue, writejpg = wvalue, DERIVATIVE=Dvalue)
            print("D... 1 argument mode sending args=",newkwargs)
            h5t.main(args[0], **newkwargs)
        if len(args)==2: # FILENAME AND ALSO THE KEY
            print("D... 2 argumets call to h5t,  pvalue=", pvalue)
            h5t.main(args[0], args[1], plot = pvalue, writejpg = wvalue, DERIVATIVE=Dvalue)


    if MODE=="org":
        print("D... convert org to h5")
        org2h5.orgme(args[0])


    if MODE=="    ":print("ok")
    if MODE=="    ":print("ok")

    return






def test_launch():
    assert launch('A')==0

if __name__=="__main__":
    print("D...        tdb_io: version:",__version__)
    Fire( launch )
