#!/usr/bin/python3

#
# This file is a part of the NsCDE - Not so Common Desktop Environment
# Author: Hegel3DReloaded
# Licence: GPLv3
#

import colorsys
import sys
import getopt

def hsv2rgb(hsv1, hsv2, hsv3):
   hsv1 = float(hsv1)
   hsv2 = float(hsv2)
   hsv3 = float(hsv3)
   r, g, b = colorsys.hsv_to_rgb(hsv1/360, hsv2/255, hsv3/255)
   # r, g, b = colorsys.hsv_to_rgb(hsv1/360, hsv2/100, hsv3/100)
   print ('%03d %03d %03d' % (int(round(r*255)), int(round(g*255)), int(round(b*255))))

def rgb2hsv(rgb1, rgb2, rgb3):
   rgb1 = int(rgb1)
   rgb2 = int(rgb2)
   rgb3 = int(rgb3)
   h, s, v = colorsys.rgb_to_hsv(rgb1/255, rgb2/255, rgb3/255)
   # print (int(round(h*360)), int(round(s*100)), int(round(v*100)))
   print ('%03d %03d %03d' % (int(round(h*360)), int(round(s*255)), int(round(v*255))))

def rgb2hex(rgb1, rgb2, rgb3, x11_16_bit):
   rgb1 = int(rgb1)
   rgb2 = int(rgb2)
   rgb3 = int(rgb3)
   if x11_16_bit == 0:
      print ('%01s%02x%02x%02x' % ("#", rgb1, rgb2, rgb3))
   if x11_16_bit == 1:
      print ('%01s%02x%02x%02x%02x%02x%02x' % ("#", rgb1, rgb1, rgb2, rgb2, rgb3, rgb3))

def usage():
    print ("colorcalc [ -R | --rgb <R/G/B> ] | [ -H | --hsv <H/S/V> ] | -x | -X | --hex <R/G/B> | -h | --help")

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "R:H:xX:h", ["rgb=", "hsv=", "16", "hex=", "help"])
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit(2)
    verbose = False
    x11_16_bit = 0
    for o, a in opts:
        if o in ("-R", "--rgb"):
           rgb1, rgb2, rgb3 = a.split("/")
           rgb2hsv(rgb1, rgb2, rgb3)
        elif o in ("-H", "--hsv"):
           hsv1, hsv2, hsv3 = a.split("/")
           hsv2rgb(hsv1, hsv2, hsv3)
        elif o in ("-X", "--hex"):
           rgb1, rgb2, rgb3 = a.split("/")
           rgb2hex(rgb1, rgb2, rgb3, x11_16_bit)
        elif o in ("-x", "--16"):
           x11_16_bit = 1
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        else:
            assert False, "getopt: unhandled option"

# Action ...
if __name__ == '__main__':
    main()

