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


'''

colorcycle
v0.1.0

A simple effect : cycle colors 

LICENCE : CC

by cocoa 


'''
from __future__ import print_function
import sys
import ast
import os
import argparse
import random
import time 
name = "filters::cycle"

argsparser = argparse.ArgumentParser(description="Redis exporter LJ")
argsparser.add_argument("-x","--centerX",help="geometrical center X position",default=300,type=int)
argsparser.add_argument("-y","--centerY",help="geometrical center Y position",default=300,type=int)
argsparser.add_argument("-m","--min",help="Lowest value in the range 0-255",default=10,type=int)
argsparser.add_argument("-M","--max",help="Highest value in the range 0-255",default=255,type=int)
argsparser.add_argument("-f","--fps",help="Frame Per Second",default=30,type=int)
argsparser.add_argument("-v","--verbose",action="store_true",help="Verbose")

args    = argsparser.parse_args()
fps     = args.fps
minVal  = args.min
maxVal  = args.max
centerX = args.centerX
centerY = args.centerY
verbose = args.verbose

optimal_looptime = 1 / fps

UP                  = 5
DOWN                = -5
currentColor        = [0,0,0]
composant           = 0
currentDirection    = UP

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

def rgb2int(rgb):
    return int('0x%02x%02x%02x' % tuple(rgb),0)

def cycleColor( pl ):

    global composant
    global currentDirection 
    # debug(name,"pl:{}".format(pl)) 
    value = currentColor[composant]
    if currentDirection == UP:
        target = maxVal
    else:
        target = minVal
    value += currentDirection
    currentColor[composant] = value

    debug(name,"currentColor:{}".format(currentColor))
    for i in range( 0, len(pl)):
        pl[i][2] = rgb2int( currentColor)

    # change the composant if target reached
    if value <= target and currentDirection == DOWN or value >= target and currentDirection == UP :
        composant = random.randint( 0,2)
        value = currentColor[composant]
        if value == 0 :
            currentDirection = UP
        else: 
            currentDirection = DOWN
    #debug( "pl:{}".format(pl)) 
    return pl 

  
try:
    while True:
      start = time.time()
      line = sys.stdin.readline()
      if line == "":
         time.sleep(0.01)
      line = line.rstrip('\n')
      pointsList = ast.literal_eval(line)
      # Do the filter
      result = cycleColor( pointsList ) 
      print( result, flush=True )
      looptime = time.time() - start
      # debug(name+" looptime:"+str(looptime))
      if( looptime < optimal_looptime ):
        time.sleep( optimal_looptime - looptime)
        # debug(name+" micro sleep:"+str( optimal_looptime - looptime))
except EOFError:
    debug(name+" break")# no more information

