#!/usr/bin/python3
# -*- coding: utf-8 -*-
# -*- mode: Python -*-

'''
toWS 
exporter to LJ via WebSocket 
v0.1b

'''
from __future__ import print_function
import websocket
import time
import argparse
import traceback
import sys

try:
    import thread
except ImportError:
    import _thread as thread


print("")
print("toWS v0.1b")
print ("Arguments parsing if needed...")
argsparser = argparse.ArgumentParser(description="toWS v0.1b help mode")
argsparser.add_argument("-v","--verbose",action="store_true",help="Verbose output")
argsparser.add_argument("-s","--server",help="WS server IP (127.0.0.1 by default)", type=str)
argsparser.add_argument("-p","--port",help="WS port to bind to (9001 by default)", type=str)
argsparser.add_argument("-k","--key",help="Redis key to update",default="0",type=str)
args = argsparser.parse_args()

key = args.key
verbose=args.verbose

name    = "exports::toWS"



# Server name
if args.server:
    serverIP = args.server
else:
    serverIP = "127.0.0.1"

# ORCA destination device
if args.port:
    wsPORT = args.port
else:
    wsPORT = 9001

def debug(*args, **kwargs):
    if( verbose == False ):
        return
    print(*args, file=sys.stderr, **kwargs)


def GetTime():
  return time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())


def on_message(ws, message):
    debug(message)

def on_error(ws, error):
    debug(error)

def on_close(ws):
    debug("### closed ###")

def on_open(ws):

    def run(*args):

        try:
            while True:
              line = sys.stdin.readline()
              if line == "":
                 time.sleep(0.01)
              line = line.rstrip('\n')
              line=line[1:-1]
              line = line.replace("[",'(')
              line = line.replace("]",')')
              #debug(line)
              line = "[{}]".format(line)
              ws.send(str(key)+' "'+line+'"')
              debug("exports::ws "+str(key)+" "+line)


        except EOFError:
            debug("break")# no more information

        finally:
            ws.close()
            print("sendWS terminating...")


    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://"+str(serverIP)+":"+str(wsPORT),
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()




    

