#!/usr/bin/env python3

#REMARKS ========================
#        ... cv2.V4L2 is used to avoid stuck while cap.read()

# to override print <= can be a big problem with exceptions
from __future__ import print_function # must be 1st
import builtins

import sys

from fire import Fire

from flashcam.version import __version__
print("i... VERSION:",__version__)

# ================================ AS EARLY AS POSSIBLE
from flashcam import config


from flashcam import usbcheck
from flashcam import direct

from flashcam import v4lc
# from flashcam.v4lc import set_gem


import json

import webbrowser
import multiprocessing
import time
import psutil
###from flashcam.real_camera import Camera
#from flask_script import Manager, Server
import subprocess as sp
import atexit

#  import flashcam.config as config

try:
    import flashcam.uniwrec as uniwrec
except:
    #print("X... cannot import uniwrec ... ?problem with pynput and Xserver")
    print("X ... cannot import uniwrec ...i go on... anyway")

import os #  for exit

import numpy as np

import datetime as dt

import requests

import shutil

import flashcam.izmq_receiver as izmq_receiver # IMAGEZMQ-DISP.py earlier

import glob
from console import fg,bg

class Bcolors:
    HEADER = '[95m'
    OKBLUE = '[94m'
    OKGREEN = '[92m'
    WARNING = '[93m'
    FAIL = '[91m'
    ENDC = '[0m'
    BOLD = '[1m'
    UNDERLINE = '[4m'


import importlib_resources

def get_data_path(filename, pkg="flashcam"):
    """
    returns full path to data stored in /data
    at the moment it only works for
    - git dir
    - .local/bin/data , that doesnt exist
    """
    #filename = "nubase2016.txt"
    ret = importlib_resources.files( pkg ).joinpath("data/"+filename)
    print(f"i... {ret}")
    return ret


def check_apts():
    """
check python3-opencv
"""
    ok = True

    try:
        import cv2
    except:
        print("!... cv2 not present: apt install python3-opencv")
        ok = False

    CMD = ['which','gunicorn']
    child = sp.Popen( CMD, stdout = sp.PIPE )
    returncode = child.returncode
    if not(returncode is None):
        print("!... gunicorn missing: pip3 install gunicorn")
        ok = False

    if not os.path.exists("/usr/bin/v4l2-ctl"):
        print("!... v4l2-ctl not present: apt install v4l-utils")
        ok = False


    if not os.path.exists("/usr/bin/scrot"):
        print("!... scrot (screenshot) not present: apt install scrot")
        ok = False



    return ok




def is_int(n):
    try:
        float_n = float(n)
        int_n = int(float_n)
    except ValueError:
        return False
    else:
        return float_n == int_n



def exit_handler():

    ok=False
    kill_gunicorn()

def GUNI():
    CMD="gunicorn -w 1 -b 0.0.0.0:8000 -k gevent --timeout 15 web:app"
    CMD="gunicorn --threads 5  -w 1 -b 0.0.0.0:8000  --timeout 15 web:app"
    print(CMD)
    proc = sp.Popen(CMD.split(), shell=False)
    print(CMD)
    proc.wait()
    proc.kill()
    return proc.pid







def kill(proc_pid):
    print(f"kiilling  {proc_pid}")
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()

def kill_gunicorn():
    CMD = f"killall -9 gunicorn"
    print("X... KIILLING", CMD)
    sp.Popen(CMD, shell = True )



def initiate_port( port ):
    config.load_config( create_if_nex = True)
    #print(f'D... wget {config.CONFIG["user"]}  --password {config.CONFIG["password"]}')
    CMD = f'wget --user  {config.CONFIG["user"]} --password {config.CONFIG["password"]} http://localhost:{config.CONFIG["netport"]}/video -O /dev/null '
    CMD = f'curl --user  {config.CONFIG["user"]}:{config.CONFIG["password"]} http://localhost:{config.CONFIG["netport"]}/video --output /dev/null '
    print("\n\n\ni... ",CMD,"\n\n\n")
    #return
    proc = sp.Popen(CMD, shell=True)
    try:
        proc.wait(timeout=4)
    except sp.TimeoutExpired:
        print("D... wget timeout expired")
    try:
        kill(proc.pid)
        print("X...   wget killed here")
    except:
        print("X...  killing wget failed")
        ##    Camera = Camera # creating the OBJECT



def copy_web2config(app_path):

    # TO config
    path,filen = os.path.split( config.CONFIG['filename'] )
    path = os.path.expanduser( path )


    if os.path.exists( path ):
        print("i... cfg path is ok")
        # FROM APP
        xapp_path = str(get_data_path( "x" ))[:-1]+"web/"  # source data

        if os.path.exists( xapp_path ):
            print(f"{bg.green} {xapp_path} {bg.default}")
        else:
            print(f"{bg.red} {xapp_path} {bg.default}")
            os.mkdir(os.path.expanduser( xapp_path ))

        DEST = f"{path}/web/"


        if os.path.exists( DEST ):
            print(f"{bg.green} {DEST} {bg.default}")
        else:
            print(f"{bg.red} {DEST} {bg.default}")
            os.mkdir(os.path.expanduser( DEST ))


        for i in glob.glob(xapp_path+"*"):
            _,ifi = os.path.split( i )
            if not os.path.exists( DEST+ ifi):
                print(f"{bg.blue} ... cp {i}  {bg.default}")
                #app_path = get_data_path( i )
                #print( app_path, ' shutil.copy(f"{app_path}" , path ) ')
                shutil.copy( i , DEST )



def copy_images2config(app_path):
    """
    I need to use the trick to find ./data/
    """
    path,filen = os.path.split( config.CONFIG['filename'] )
    path = os.path.expanduser( path )
    if os.path.exists( path ):
        print("i... cfg path is ok")

        xapp_path = get_data_path( "x" )

        for i in ["BEAM_OFF.jpg","BEAM_ON_.jpg","DET_NRDY.jpg",
                  "DET_RDY_.jpg","monoskop.jpg",
                  "windows.jpg",
                  "win_rain.jpg",
                  "win_skull.jpg",
                  "win_storm.jpg",
                  "win_winter.jpg",
                  "small_pixel.ttf",
                  "digital-7.mono.ttf"]:
            fuln = path+"/"+i
            if not os.path.exists( fuln ):

                app_path = get_data_path( i )

                print(f"i...  copying ... from {app_path} to {fuln}")
                shutil.copy(f"{app_path}" , path )
        print(f"i... jpgs {xapp_path} to {path} should be copied now")
    else:
        print(f"X... config path /{path}/ doesnt exist")

    return



#=============================================================
#
#                   MAIN
#
#=============================================================
def main(cmd = None,
         product = None,
         resolution = None,
         framekind = None,
         FOURCC = None,
         PIXELFORMAT = None,
         threshold = None,
         average = None,
         blur = None,
         laps = None,
         web5000 = None,
         expo = None,
         gain = None,
         mmaga = None,
         Histogram = None,
         imagezmq = None,
         jtelegram = None,
         kompress = None,
         save = None,
         qpassfile = None,
         otate = None,
         x = None,
         y = None,
         debug = None,
         vof = None, # framekind already taken
         zoom = None,
         XY = "1x1",
         netport = None,
         help = None
):

    cmd = str(cmd) # also 5000 is command now
    print(f"1=============================================== cmd == {cmd} =====================================================")

    helptext = """ Main function of the project, alphabetical order
|    |                                           |     |
| -a | average  averaging                        |   6 |
| -b | blur                                      |   7 |
| -c | command                                   |   2 |
| -d | debug                                     |   1 |
| -e | expo ( in v4l )                           |  11 |
| -f | framekind  target_frame                   |   5 |
| -F | FOURCC                                    |     |
| -g | gain                                      |  12 |
| -H | Histogram (show mean in image)            |  14 |
| -i | imagezmq                                  |     |
| -j | telegram (no letter free)                 |     |
| -k | compression of the stream                 |  95 |
| -l | laps                                      |   9 |
| -m | gamma                                     |  13 |
| -n | net port ... override 5000/8000           |     |
| -o | rOtate                                    |  19 |
| -p | product/pathID                            |   3 |
| -P | PIXELFORMAT ...YUYV MJPG                  |     |
| -q | passfile in UNI                           |  16 |
| -r | resolution                                |   4 |
| -s | in UNI save AVI                           |  15 |
| -t | threshold                                 |   8 |
|    |                                           |     |
| -v | FOV field of View in degrees              | 101 |
| -w | web5000 ... view flask                    |  10 |
| -x | speed of translation for astrophotography |  17 |
| -X | XY                                        |     |
| -y | speed of translation for astrophotography |  18 |
| -z | zoom                                      |  20 |
|    | n   u                                     |     |
| -h | help                                      |     |
    """

    all_commands = ["usage","savecfg","save","flask","ask",
                    "show", "ls" , "getres" ,
                    "v4l", "uni","zmq","zmqv","zmqs",
                    "test"]

    if help is not None:
        print(helptext)
        print("COMMANDS:", all_commands)
        print("""
        ls        ... see available cameras, IDPath (use in -p)
        getres    ... show resolutions available for product
        show      ... direct show
        flask     ... start flask on port -n xxx (or config value), consider -w; also 'flask'
        ask       ... wget ... prepare to start gunicorn!!!=flashcamg;
        savecfg   ... save commandline parameters to config
        v4l       ...
        uni       ... uninteruptible stream: uni http://192.168.0.91:8000/video
        zmqv      ... wait imagezmq receive + display + avi
        zmqs      ... wait imagezmq receive silent avi
        """)
        sys.exit(0)

    if not (cmd in all_commands):
        print(f"X... unknown command {cmd} !! ... Possible commands:",  all_commands)
        sys.exit(1)


    print("i... python path",os.path.realpath(sys.executable))

    if getattr(sys, 'frozen', False):
        application_path = os.path.dirname(sys.executable)
    elif __file__:
        application_path = os.path.dirname(__file__)
    print("i... application path",application_path)


    #sys.exit(0)

    # REMEMBER -WEBPY IS MAIN--------------------
    if not check_apts():
        sys.exit(1)

    copy_images2config( application_path )
    copy_web2config(    application_path)


    # CONFIG IS LOADED AT THIS MOMENT
    # from flashcam import web # THIS IS THE MOST IMPORTANT PART:CONFIG LOAD

    # I CHECK THE PARAMETERS-REQUIRING-VALUES
    #print(f"gain = {gain}")
    #print(f"expo = {expo}")
    #print(f"mmaga = {mmaga}")

    # HERE I DEFINE DEFAULTS.
    main_defaults={}
    main_defaults["product"]=""
    main_defaults["resolution"]="640x480"
    main_defaults["framekind"] = "direct"
    main_defaults["FOURCC"] = "DIVX"
    main_defaults["PIXELFORMAT"] = "YUYV" # MJPG , YUYV
    main_defaults["threshold"] = 0
    main_defaults["average"] = 0
    main_defaults["blur"] = 0
    main_defaults["laps"] = -1
    main_defaults["web5000"] = False
    main_defaults["expo"] = "auto"
    main_defaults["gain"] = -1
    main_defaults["mmaga"] = -1
    main_defaults["Histogram"] = False
    main_defaults["imagezmq"] = None
    main_defaults["jtelegram"] = False
    main_defaults["kompress"] = 95
    main_defaults["save"] = False,  # for UNI
    main_defaults["qpassfile"] = "~/.pycamfw_userpass"
    main_defaults["otate"] = False # for UNI, also for CONFIG, also for show
    main_defaults["x"] = 0
    main_defaults["y"] = 0
    main_defaults["debug"]=False
    main_defaults["vof"]="101,-1" # negative means uni will not display
    main_defaults["zoom"]=1
    main_defaults["netport"]=8000

    main_defaults["XY"]="1x1"

    # ACTUALS - get from commandline
    main_actual={}
    main_actual["product"]=product
    main_actual["resolution"]=resolution
    main_actual["framekind"] = framekind
    main_actual["FOURCC"] = FOURCC
    main_actual["PIXELFORMAT"] = PIXELFORMAT
    main_actual["threshold"] = threshold
    main_actual["average"] = average
    main_actual["blur"] = blur
    main_actual["laps"] = laps
    main_actual["web5000"] = web5000
    main_actual["expo"] = expo
    main_actual["gain"] = gain
    main_actual["mmaga"] = mmaga
    main_actual["Histogram"] = Histogram
    main_actual["imagezmq"] = imagezmq
    main_actual["jtelegram"] = jtelegram
    main_actual["kompress"] = kompress
    main_actual["save"] = save  # for UNI
    main_actual["qpassfile"] = qpassfile
    main_actual["otate"] = otate # for UNI, also for CONFIG, also for show
    main_actual["x"] = x
    main_actual["y"] = y
    main_actual["debug"]=debug
    main_actual["vof"]=vof
    main_actual["zoom"]=zoom
    main_actual["netport"]=netport

    main_actual["XY"]=XY

    #----- check -- invalids --------------------------------------
    #      except  bool types:  True/False ------------------------
    for k,v in main_actual.items():
        if ( type(v) == bool) and not(k in ['web5000','Histogram','save','otate','debug','jtelegram']):
            print(f"!... missing a value for parameter {k}: ... incorrect suggested value is: {v}")
            sys.exit(1)

    print(f"2=============================================== cmd == {cmd} =====================================================")


    # ----- print nicely AND UPDATE config. CONFIG is MAIN_ACTUAL now----------------
    for k,v in main_actual.items():
        if v is not None: # value injected
            print(f"i...                       =====>{fg.white} | {k:>13s} | {str(v):20s} | {fg.default}")
            config.CONFIG[k] = v  # UPDATE HERE


    print(f"3=============================================== cmd == {cmd} =====================================================")


    if not cmd == "uni":
        # RESOLUTION CHECK---------------
        if main_defaults['resolution'] != config.CONFIG['resolution']:
            recomvid = usbcheck.recommend_video( product )
            print(f"i... FORCED checking resolution for video {product} ... {recomvid}")
            if len(recomvid)>0:
                resolutions = usbcheck.get_resolutions( recomvid[0] )
            else:
                resolutions = []
                print(f"X... {bg.red}{fg.white} BAD VIDEOSOURCE {fg.default}{bg.default}")
                sys.exit(0)
            if config.CONFIG['resolution'] not in resolutions:
                print(f"X... {bg.red}{fg.white} {config.CONFIG['resolution']} ISBAD RESOLUTION {resolutions}{fg.default}{bg.default}")
                print(f"X... you have a forced resolution in config that is not available. Override with '-r 640x480'")
                sys.exit(0)

    print(f"4=============================================== cmd == {cmd} =====================================================")

    #----- check --invalids -------------------------
    if (config.CONFIG["threshold"]>0) and (config.CONFIG["blur"]==0) and (config.CONFIG["average"]<2):
        print("X... cannot be -thr>0 and blur ==0  and  average==0,1")
        sys.exit(1)



    # #problematic - i cannot SAVE directly, it rewrites the changes

    # #======================= I copy this to webpy so that gunicorn runs ok
    # if not debug:
    #     # print("X... NO DEBUG colors in main")
    #     _print = print # keep a local copy of the original print
    #     builtins.print =lambda *args, **kwargs:  None  if (isinstance(args[0], str)) and (args[0].find("D...")==0) else  _print( *args, **kwargs) if ('file' in kwargs) else _print( "{}".format(Bcolors.FAIL   if ((isinstance(args[0], str)) and (args[0].find("X...")>=0)) else Bcolors.ENDC) , *args, Bcolors.ENDC, **kwargs, file=sys.stderr)
    # else:
    #     print("X... DEBUG COLORS FROM MAIN")
    #     # debug - show all + colors
    #     _print = print # keep a local copy of the original print
    #     builtins.print =lambda *args, **kwargs:   _print( *args, **kwargs) if ('file' in kwargs) else _print( "{}".format(Bcolors.FAIL   if ((isinstance(args[0], str)) and (args[0].find("X...")>=0)) else Bcolors.OKGREEN if  ((isinstance(args[0], str)) and (args[0].find("i...")>=0)) else Bcolors.ENDC  ), *args, Bcolors.ENDC, **kwargs, file=sys.stderr)

    #======== DEFINE THE CONFIG FILE HERE ========
    #========   NONONONO   NO              ======
    #======== in this case, all config handling must be win webpy
    #------- as it is the second ENTRY point
    #-------- and the only for gunicorn -----------------











    print(f"x============================================== cmd == {cmd} =====================================================")
    if cmd == "usage":
        print(''' ... usage:
    flashcam command [options]
_____________________________________________________
    commands:
        ls        ... see available cameras, IDPath (use in -p)
        getres    ... show resolutions available for product
        show      ... direct show
        flask     ... start flask on port -n xxx, consider -w; also 'flask'
        savecfg   ... save commandline parameters to config
        v4l       ...
        uni       ... uninteruptible stream: uni http://192.168.0.91:8000/video
        zmqv      ... wait imagezmq receive + display + avi
        zmqs      ... wait imagezmq receive silent avi
_____________________________________________________
    options:                         EXAMPLE:
        -p ... product/ IDPath / jpg   | -p 14.0-usb-0:2:1.0
                                       | -p screenshot.jpg
        -r ... resolution (see getres) | -r 320x240
        -a ... accumulation* : n frames| -a 10
        -b ... blur* : blur the frame  | -b 3
        -t ... threshold for motiondet | -t 100
        -f ... frame kind (direct,delta*,detect*,histo)
        -F ... FOURCC codec laps       | -F DIVX,IYUV
        -P ... PIXELFORMAT             | -P YUYV, MJPG
        -H ... show a mean histo value | -H
        -l ... save timelaps [seconds] | -l 3600
        -w ... open web (for flask    )| -w
        -e ... exposure (0-1;auto)     | -e 0.02
        -g ... gain     (0-1; default) | -g 0.1
        -m ... gamma    (0-1;default)  | -m 0.1
        -q ... passfile for UNI        | -q ~/.pycamfw_userpass
        -x ... move image in x ( -y)   | -x 0.01
           ... <1 is speed/s >1 fixed  | -x -200 -y 100
        -o ... rotate by N degrees     | -o 180
           ...  -x,-y>1 = center       | -x 100 -y 10 -o 30
        -z ... zoom (center from cross)| -z 2
        -d ... debug info
        -s ... save avi in UNI         | -s
        -X ... winpos for UNI          | -X 1x1
 _____________________________________________________
       * usefull with -t
''')
        sys.exit(0)

    elif cmd == "uni":
        uniok = True
        print("==================================================== UNI =======================================================")
        # ADDRESS AND PORT
        product2 = str(product)

        if os.path.exists( product2): # i can see a file
            print(" PLAY FILE ")
            print(" PLAY FILE ". product2)
            if 'uniwrec' in globals():
                print("D... uniwrec calling display2 - path exists", product2)
                uniwrec.display2( product2, save = save, passfile = qpassfile, rotate = otate, vof = str(config.CONFIG['vof']), XY=config.CONFIG["XY"])
            else:
                print("X... problem with uniwrec.display2:  ? maybe pynput? no Xserver...")
            sys.exit(0)



        if (product2 == None) or (product2=="None"):
            product2 = "http://127.0.0.1:8000/video"
            uniok = False
        elif is_int(product2) and int(product2)<65300 and int(product2)>79:
            product2 = f"http://127.0.0.1:{product2}/video"



        # (product2 == "5000") or (product2 == ":5000") :
        #     product2 = "http://127.0.0.1:5000/video"
        #     uniok = False
        # if (product2 == "8000") or (product2 == ":8000") :
        #     product2 = "http://127.0.0.1:8000/video"
        #     uniok = False


        dots = len( product2.split(".") )
        if dots == 4:
            print("i... IP address detected ")
            if product2.find("http://")!=0:
                prt = len( product2.split(":") )
                if prt == 1:
                    product2 = f"{product2}:8000"

        if product2.find("http://")!=0:
            product2= "http://"+product2
            uniok = False

        if (product2.find("/video")!= len(product2)-len("/video")):
            product2+= "/video"
            uniok = False

        # if only IP given

        print( product2 )
        print( product2 )
        print( product2 )
        print( product2 )

        #if ((product2.find(":8000")>0)or(product2.find(":5000")>0) ) \


        # elif product2.find("000/video")!= len(product2)-len("000/video"):
        #     product2+= ":8000/video"
        #     uniok = False
        #     print( product2 )
        #     print( product2 )
        #     print( product2 )
        #     print( product2 )
        #     print( product2 )
        #     print( product2 )

        if not uniok:
            #print("a")
            print(f"i... ADDRESS CHANGED FROM {product} TO : {product2}")

        print("D... play something:", product2 )
        if 'uniwrec' in globals():
            uniwrec.display2( product2, save = save, passfile = qpassfile, rotate = otate, vof = str(config.CONFIG['vof']), XY=config.CONFIG["XY"])  # i can see a stream
        else:
            print("X... problem with uniwrec - not in globals()? ? pynput? no Xserver...")
        sys.exit(0)




    elif cmd == "v4l":

        recomvid = usbcheck.recommend_video( product )

        cc = v4lc.V4L2_CTL("/dev/video"+str(recomvid[0]))
        output = v4lc.get_resolutions( recomvid[0]  )
        print(f"i... /dev/video{recomvid[0]}: result== {output}")
        #print(cc._list_controls())

        print(f"required gain  = {gain}")
        print(f"required expo  = {expo}")
        print(f"required gamma = {mmaga}")

        post_addr5 = "http://127.0.0.1:5000/cross"
        post_addr = "http://127.0.0.1:8000/cross"
        print("! ... sending to both addresses:")
        print(f"! ... {post_addr}")
        print(f"! ... {post_addr5}")
        post_data = None

        if (gain!=-1) and not(gain is None):
            if gain=="def":
                post_data = {'gain':'GAIN'}
            else:
                post_data = {'gainset':'GAINSET','gainvalue': float(gain) }

        if not (post_data is None):
            try:
                post_response = requests.post(url=post_addr, data=post_data)
            except:
                pass
            try:
                post_response = requests.post(url=post_addr5, data=post_data)
            except:
                pass
            time.sleep(1)
            post_data = None


        if (expo!=-1) and not(expo is None):
            if expo=="def":
                post_data = {'expo':'EXPO'}
            elif expo=="auto":
                post_data = {'expo':'EXPO'}
            else:
                post_data = {'exposet':'EXPOSET','expovalue': float(expo) }
        if not (post_data is None):
            try:
                post_response = requests.post(url=post_addr, data=post_data)
            except:pass
            try:
                post_response = requests.post(url=post_addr5, data=post_data)
            except:
                pass

        # - i need to go through web interface....
        #v4lc.set_gem(cc, gain, expo, mmaga)
        # print(f"gain = {gain}")
        # print(f"expo = {expo}")
        # print(f"mmaga = {mmaga}")



        #post_addr = videodev.replace("/video","/cross" )
        #post_data = {'expo2':'EXPO2'}
        #post_response = requests.post(url=post_addr, data=post_data)

        sys.exit(0)




    elif cmd == "ls":
        usbcheck.recommend_video()
        sys.exit(0)

    elif (cmd == "savecfg") or (cmd=="save"):   # i dont have it loaded ....
        # print( "i... USER  bin_fla:", config.CONFIG['user'] )
        # config.CONFIG['target_frame'] = framekind
        # config.CONFIG['threshold'] = threshold
        # config.CONFIG['timelaps'] = laps
        # config.CONFIG['average'] = average
        # config.CONFIG['blur'] = blur
        # config.CONFIG['histogram'] = histogram
        # config.CONFIG['x'] = x
        # config.CONFIG['y'] = y

        # config.CONFIG['rotate180'] = otate

        # config.CONFIG['expo'] = expo
        # config.CONFIG['gamma'] = mmaga
        # config.CONFIG['gain'] = gain

        print("i... Configuration SAVING")
        config.save_config()
        print("i... Configuration SAVED")
        sys.exit(0)

    # elif cmd == "show2":
    #     recomvid = usbcheck.recommend_video( product )
    #     # usbcheck.show_cam( recomvid[0], res, recommended= product)

    # --------------------------------------------------





    elif cmd == "show":

        recomvid = usbcheck.recommend_video( product )

        # config.CONFIG["recommended"] = recomvid
        # config.CONFIG['timelaps'] = laps
        # config.CONFIG['target_frame'] = framekind
        # config.CONFIG['threshold'] = threshold
        # config.CONFIG['average'] = average
        # config.CONFIG['blur'] = blur
        # config.CONFIG['histogram'] = histogram
        # config.CONFIG['resolution'] = res
        # config.CONFIG['x'] = x
        # config.CONFIG['y'] = y
        # config.CONFIG['rotate180'] = otate

        # config.CONFIG['expo'] = expo
        # config.CONFIG['gain'] = gain
        # config.CONFIG['gamma'] = mmaga

        # v4lc.set_gem(cc, gain, expo, mmaga)


        direct.show_cam( )

        sys.exit(0)


    # ------------------------------------------------------------------------------
    elif cmd == "getres":
        recomvid = usbcheck.recommend_video( product )
        print(f"i... checking resolution for video {recomvid[0]}")
        # should be v4lc.
        resolutions = usbcheck.get_resolutions( recomvid[0] )
        print(resolutions)
        sys.exit(0)
    # ------------------------------------------------------------------------------
    elif cmd == "ask":
        print("i... NOT STARTING flask NOT STARTING GUNICORN")

        CMD="gunicorn --threads 5  -w 1 -b 0.0.0.0:8000  --timeout 15 web:app"
        print(CMD)
        print(CMD)
        print(CMD)
        print("i... now i ONLY try to initiate the port 8000 and I quit")
        print("i... now i ONLY try to initiate the port 8000 and I quit")
        print("i... now i ONLY try to initiate the port 8000 and I quit")
        time.sleep(4)
        initiate_port(8000)
        sys.exit(0)

    # ------------------------------------------------------------------------------
    elif cmd == "zmqv":
        print("i... receiver of imagezmq (earlier imagezmq-disp.py) + DISPLAY")
        izmq_receiver.main( True )
        sys.exit(0)

    elif cmd == "zmqs":
        print("i... receiver of imagezmq (earlier imagezmq-disp.py) SILENT")
        izmq_receiver.main( False )
        sys.exit(0)

    elif cmd == "zmq":
        print("\ni... for receiver of imagezmq use zmqv or zmqs")
        sys.exit(0)


    # ------------------------------------------------------------------------------
    elif cmd == "flask" :

        print(f"i... flask starting on port {config.CONFIG['netport']} - multiprocessing with target=API")
        p = multiprocessing.Process(target=API) # it keeps the config???/ it shuld...
        p.start()
        if web5000:
            webbrowser.open(f"http://localhost:{config.CONFIG['netport']}")
        else:
            time.sleep(3)
            initiate_port(config.CONFIG['netport'])


    # ------------------------------------------------------------------------------
    elif cmd == "test":   # PALY GAMES
        print("i... test")
        recomvid = usbcheck.recommend_video( product )

        cc = v4lc.V4L2_CTL("/dev/video"+str(recomvid[0]))
        output = v4lc.get_resolutions( recomvid[0]  )
        print(f"i... /dev/video{recomvid[0]}: result== {output}")
        #print(cc._list_controls())

        now = dt.datetime.now()
        now = f"{now}".replace(" ","_")


        direct.get_frame( )
        for i in np.arange(np.log(0.001), np.log(1),0.1):
            expo = np.exp( i )
            print(f"required gain  = {gain}")
            print(f"required expo  = {expo}")
            print(f"required gamma = {mmaga}")
            v4lc.set_gem(cc, gain, expo, mmaga )
            hmean = direct.get_frame( )
            if hmean[-1].upper()=="B": hmean = hmean[0:-1]
            if hmean[-1].upper()=="W": hmean = hmean[0:-1]
            print(f"i..............{expo:.3f}............... {hmean}")
            print(f"i..............{expo:.3f}............... {hmean}")
            print(f"i..............{expo:.3f}............... {hmean}\n")
            with open(f"calib{now}.txt","a") as f:
                f.write(f"{expo:.4f} {hmean}\n")
            #time.sleep(1)
        hmean = direct.get_frame(last=True )


        time.sleep(1)
        v4lc.set_gem(cc, "def", "auto", "def" )
        sys.exit(0)

    else:
        print("X... NO COMMAND GIVEN, ENDING")
        #unitname.func()




from flashcam import web # THIS IS THE MOST IMPORTANT PART:CONFIG LOAD
#  porblem continues. when I launch webpy, it again reads config
# ======================== THIS IS THE ENTRY POINT FOR FLASK
def API():
   print('i... RUNNING INSIDE  API : PORT TO RUN ON: ',config.CONFIG['netport'])
   web.app.run(host='0.0.0.0', port=config.CONFIG['netport'], threaded=True)



if __name__=="__main__":
    #print("i... check apt :  v4l-utils gunicorn and pip3 gevent")
    Fire(main)
