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

'''
tonano 
input space for X & Y : -1500,+1500
exporter to LJ nano
v0.1b

a la place de ast.literal_eval(line) : ?

>>> a = "[[111.121, 45.8783, 0.0],[110.936, 44.8368, 0.0],[374.849, 673.228, 230.536]]"
>>> import json
>>> b = json.loads(a)
>>> b
[[111.121, 45.8783, 0.0], [110.936, 44.8368, 0.0], [374.849, 673.228, 230.536]]
>>> b[0]
[111.121, 45.8783, 0.0]

'''
from __future__ import print_function
import websocket
import time
import argparse
import traceback
import sys
import random
from websocket_server import WebsocketServer
from socket import *
#import ast

try:
    import thread
except ImportError:
    import _thread as thread

name = "exports::tonano"

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


argsparser = argparse.ArgumentParser(description="tonano 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="/pl/0/0",type=str)
argsparser.add_argument("-o","--old",help="Coordinates in old school 0-800 space",action="store_true")
args = argsparser.parse_args()

key = args.key

if args.verbose:
    verbose = True
else:
    verbose = False

if args.server:
    serverIP = args.server
else:
    serverIP = "127.0.0.1"

if args.port:
    wsPORT = args.port
else:
    wsPORT = 9001

if args.old:
    inspace = [0,800]
else:
    inspace = [-1500,1500]


outspace = [-1500,1500]
zoom = (outspace[1]-outspace[0])/(inspace[1]-inspace[0])

debug("")
debug("tonano v0.1b")

points0 = "[(150.0, 230.0, 65280), (170.0, 170.0, 65280), (230.0, 170.0, 65280), (210.0, 230.0, 65280), (150.0, 230.0, 65280)]"
points1 = "[(180.0, 230.0, 65280), (200.0, 170.0, 65280), (180.0, 230.0, 65280)]"
points2 = "[(170.0, 190.0, 65280), (200.0, 170.0, 65280), (230.0, 190.0, 65280), (230.0, 200.0, 65280), (170.0, 230.0, 65280), (230.0, 230.0, 65280)]"
points3 = "[(170.0, 170.0, 65280), (200.0, 170.0, 65280), (230.0, 190.0, 65280), (200.0, 200.0, 65280), (230.0, 210.0, 65280), (200.0, 230.0, 65280), (170.0, 230.0, 65280)]"
points = [points0, points1, points2, points3]

LaserNumber = 1
SceneNumber = 0
Laser = 0

def sendbroadcast():

    debug("Sending broadcast")
    cs = socket(AF_INET, SOCK_DGRAM)
    cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
    cs.sendto("LJ tonano v0.1".encode(), ("255.255.255.255", 54545))


#
# CLI websocket client -> WS server (nanoLJ) -> webpage
#

def on_message(ws, message):
    if random.randint(0,100)>95:
        sendbroadcast()
    #debug("CLI WS client received and dropped "+message)

def on_error(ws, error):
    debug("CLI WS client got error :"+error)

def on_close(ws):
    debug("### CLI WS client WS closed ###")

def on_open(ws):

    def run(*args):

        try:
            while True:
              line = sys.stdin.readline()
              if line == "":
                 time.sleep(0.005)

              #debug("CLI string", line)
              line = line.rstrip('\n')
              line=line[1:-1]
              line = line.replace("[",'(')
              line = line.replace("]",')')
              #debug(line)
              line = "[{}]".format(line)
              
              if zoom != 1.0:
                shape = []
                pointsList = ast.literal_eval(line)
                for point in pointsList:
                  shape.append(((point[0]*zoom)+outspace[0],(point[1]*zoom)+outspace[0], point[2]))
                line = str(shape)
              
              debug("CLI proccess sending : /simul" +" "+ line)
              #sendWSall("/simul" +" "+ str(points[laserid].decode('ascii')))
              ws.send("/simul "+line)


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

        finally:
            ws.close()
            debug("tonano WS terminating...")


    thread.start_new_thread(run, ())

def handle_timeout(self):
    self.timed_out = True


#
# Launch WS CLI client
#

if __name__ == "__main__":

    try:

        # CLI Websocket client
        debug("Launching tosimu CLI websocket client...")
        #websocket.enableTrace(True)
        websocket.enableTrace(False)
        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()

    except Exception:
        debug("tonano Exception")
        traceback.print_exc()
    




