#! /usr/bin/python3
from datetime import datetime
from redis import Redis
import argparse
import json
import os
import sys

modeList = {
  "list"      : ["l","list"],
  "delete"    : ["d","delete"],
  "exit"      : ["x","q","exit"],
  "preview"   : ["p","preview"],
}

argsparser = argparse.ArgumentParser(description="manager")
argsparser.add_argument("-m","--mode",help="The action to perform. One of : {}".format(", ".join(modeList.keys())),default="list",type=str)
argsparser.add_argument("-P","--path",help="clitools path",default="~/code/lj-nano/clitools",type=str)
argsparser.add_argument("-i","--ip",help="IP address of the Redis server ",default="127.0.0.1",type=str)
argsparser.add_argument("-p","--port",help="Port of the Redis server ",default="6379",type=str)
args      = argsparser.parse_args()
mode      = args.mode
clipath   = args.path
port      = args.port
ip        = args.ip

r         = Redis(host=ip, port=port)

hashList = []

def refreshList():
  global hashList
  hashList = {}
  theList = r.hgetall("images")
  for i in theList:
    item = json.loads(theList[i])
    theList[i] = item

  # Sort by reverse Date
  for i in sorted(theList.items(),key=lambda x: x[1]['created_at'],reverse=True):
    hashList[i[0].decode("ascii")] = i[1]


while True:
  refreshList()
  if mode in modeList["list"] :
    print("hash\t\t\tdate\t\t\tpoints info")
    for i in hashList:
      item = hashList[i]
      pl = item["points_list"]
      created_at = item["created_at"]
      print("{}\t{}\t{} points".format(i,datetime.ctime(datetime.fromtimestamp(created_at)),len(pl)))

  elif mode in modeList["delete"]:
    print("Select a hash to delete")
    hash_name = input()
    result = r.hdel("images",hash_name)
    print("Result: {}".format(result))

  elif mode in modeList["preview"]:
    print("Select a hash to preview")
    hash_name = input()
    item = json.loads(hashList[bytes(hash_name,'ascii')])
    points_list = json.dumps(item["points_list"])
    bashCommand = "while true; do echo '"+points_list+"'; sleep 0.5; done | /usr/bin/python3 "+clipath+"/exports/tosimu.py"
    os.system(bashCommand)

  elif mode in modeList["exit"]:
    break

  print("Next action? (l)ist (d)elete e(x)it (p)review")
  mode = input()
