import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from lib.spectrum import *
import math

ref = getRefData()

xs = interpolate(ref["wavelength"],
                   ref["xbar"])    
ys = interpolate(ref["wavelength"],
                   ref["ybar"])    
zs = interpolate(ref["wavelength"],
                   ref["zbar"])    

w = 400
h = 400
img = np.ones((w,h,3))

def fill(i,j,r,g,b):
    img[i,j,0] = r
    img[i,j,1] = g
    img[i,j,2] = b

def fill_circle(i,j,r,g,b,size=4):
    # Half of size = si
    si = int(size/2)
    for k in range(i-si,i+si):
        for l in range(j-si,j+si):
            if(math.sqrt((k-i)**2 + (l-j)**2) <= si):
                fill(k,l,r,g,b)
            

def color_line(X,Y,Z):
    points_num = 20 + int(15*Y)
    for k in range(0,points_num):
        d = k / points_num
        i = int((d * X + (1-d) / 3) * w)
        j = int((d * Y + (1-d) / 3) * h)
        
        fill_circle(
            i,
            j,
            1-d + d * X,
            1-d + d * Y,
            1-d + d * Z,
            8
        )

# get X,Y,Z for point number i
def XYZ(i):
    X = xs[i][1] / ( xs[i][1] + ys[i][1] + zs[i][1] )
    Y = ys[i][1] / ( xs[i][1] + ys[i][1] + zs[i][1] )
    Z = zs[i][1] / ( xs[i][1] + ys[i][1] + zs[i][1] ) 
    return X,Y,Z

# get image coords for ith point in the horseshoe border
def ij(i):
    X,Y,Z = XYZ(i)
    i = int(X * w)
    j = int(Y * h)
    return i,j

# Find xy for every wavelength to find borders of horseshoe
for i in range(0,len(xs)):
    X,Y,Z = XYZ(i)
    i = int(X * w)
    j = int(Y * h)
    # color line to this end
    color_line(X,Y,Z)

for i in range(0,len(xs)):
    X = xs[i][1] / ( xs[i][1] + ys[i][1] + zs[i][1] )
    Y = ys[i][1] / ( xs[i][1] + ys[i][1] + zs[i][1] )
    Z = zs[i][1] / ( xs[i][1] + ys[i][1] + zs[i][1] ) 
    i = int(X * w)
    j = int(Y * h)
    # draw horseshoe shape
    fill_circle(i,j,0,0,0,6)

# Find end of horseshoe
i_0,j_0 = ij(0)
X_0,Y_0,Z_0 = XYZ(0)
i_last, j_last = ij(-1)
X_last,Y_last,Z_last = XYZ(-1)

# precision of bottom border
bottom_num = 50

# draw bottom border and fill colors of lines to border
for el in range(0,bottom_num):
    k = el/bottom_num
    # interpolate i,j
    i = int(k * i_0 + (1-k) * i_last)
    j = int(k * j_0 + (1-k) * j_last)
    X = k * X_0 + (1-k) * X_last
    Y = k * Y_0 + (1-k) * Y_last
    Z = k * Z_0 + (1-k) * Z_last

    color_line(X,Y,Z)
    fill_circle(i,j,0,0,0,6)
    

img = np.rot90(img)
plt.imshow(img,extent=(0,1,0,1),interpolation='bicubic')

#plt.bar(x,y)

plt.show()

