#pyinstaller --onefile

import socket
import sys,os
import threading
import time
import numpy as np
import math
from PIL import Image,ImageTk
from functools import partial
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk


root = tk.Tk()
root.title("DCS Bearing Range Calculator")
root.iconbitmap("images\\f14.ico")

root.geometry('600x450+100+200')
root.minsize(500, 400)
 
# set maximum window size value
root.maxsize(500, 400)




frame = tk.Frame(root, width=200, height=100)
frame.pack()
frame.place(anchor='center', relx=0.5, rely=0.5)

# Create an object of tkinter ImageTk
img = ImageTk.PhotoImage(Image.open("images\\rose.png"))

# Create a Label Widget to display the text or Image
label = tk.Label(frame, image = img)
label.pack()

x = tk.IntVar()
y = tk.IntVar()


labelNum1 = tk.Label(root, text="X").grid(row=1, column=5)
labelNum2 = tk.Label(root, text="Z").grid(row=3, column=5)
labelNum3 = tk.Label(root, text="Bearing from BullsEye").grid(row=1, column=0)
labelNum4 = tk.Label(root, text="Range from BullsEye").grid(row=3, column=0)
labelResult1 = tk.Label(root, text=x)
labelResult2 = tk.Label(root, text=y)
labelResult3 = tk.Label(root, text=0)
labelResult4 = tk.Label(root, text=0)


labelResult1.grid(row=1, column=7)
labelResult2.grid(row=3, column=7)
labelResult3.grid(row=1, column=1)
labelResult4.grid(row=3, column=1)



b1 = tk.Button(text="Connect")
b2 = tk.Button(text="Exit")
b4 = tk.Button(root, text="Bearing | Range")
b5 = tk.Button(root, text="Set Ref Point BullsEye")
b1.grid(row=23, column=0)
b2.grid(row=25, column=0)
b4.grid(row=8, column=1)
b5.grid(row=22, column=0)

TB = tk.IntVar()
TR = tk.IntVar()
xt = tk.IntVar()
yt = tk.IntVar()
xbulls = tk.IntVar()
ybulls = tk.IntVar()


labelNum9 = tk.Label(root, text="Target Bearing from BullsEye").grid(row=5, column=0)
labelNum10 = tk.Label(root, text="Target Range from BullsEye").grid(row=6, column=0)
entryNum9 = tk.Entry(root, textvariable=TB).grid(row=5, column=1)
entryNum10 = tk.Entry(root, textvariable=TR).grid(row=6, column=1)

labelNum1 = tk.Label(root, text="X").grid(row=5, column=5)
labelNum2 = tk.Label(root, text="Z").grid(row=6, column=5)
labelResult5 = tk.Label(root, text=xt)
labelResult6 = tk.Label(root, text=yt)
labelResult5.grid(row=5, column=7)
labelResult6.grid(row=6, column=7)

labelNum7 = tk.Label(root, text="Bearing to Target").grid(row=10, column=0)
labelNum8 = tk.Label(root, text="Range to Target").grid(row=11, column=0)
labelResult7 = tk.Label(root, text=0)
labelResult8 = tk.Label(root, text=0)
labelResult7.grid(row=10, column=1)
labelResult8.grid(row=11, column=1)


xtname = labelResult5.cget("text")
xt = int(labelResult5.getvar(xtname))

ytname = labelResult6.cget("text")
yt = int(labelResult6.getvar(ytname))


labelNum11 = tk.Label(root, text="X BullsEye").grid(row=20, column=0)
labelNum12 = tk.Label(root, text="Z BullsEye").grid(row=21, column=0)
entryNum11 = tk.Entry(root, textvariable=xbulls).grid(row=20, column=1)
entryNum12 = tk.Entry(root, textvariable=ybulls).grid(row=21, column=1)
labelNum13 = tk.Label(root, text="X").grid(row=20, column=5)
labelNum14 = tk.Label(root, text="Z").grid(row=21, column=5)
labelResult13 = tk.Label(root, text=xbulls)
labelResult14 = tk.Label(root, text=ybulls)
labelResult13.grid(row=20, column=7)
labelResult14.grid(row=21, column=7)


labelResult15 = tk.Label(root, text=x)
labelResult15.grid(row=23, column=1)






if getattr(sys, 'frozen', False):
    application_path = os.path.dirname(sys.executable)
    running_mode = 'Frozen/executable'
else:
    try:
        app_full_path = os.path.realpath(__file__)
        application_path = os.path.dirname(app_full_path)
        running_mode = "Non-interactive (e.g. 'python myapp.py')"
    except NameError:
        application_path = os.getcwd()
        running_mode = 'Interactive'

def bulls (x, y):
    xb = str(x.get())
    yb = str(y.get())
    
    config_name = "logs\BullsEyeRef.txt"
    config_full_path = os.path.join(application_path, config_name)
    log_file = open(config_full_path, "w")
    log_file.write(str(x.get()) + "\n" + str(y.get()))
    log_file.close()
    labelResult13.config(text=xb)
    labelResult14.config(text=yb)
    return x,y
bulls = partial(bulls, xbulls, ybulls)    
    
    
def rect(labelResult5, labelResult6, r, theta, x, y):
    """theta in degrees
    
    returns tuple; (float, float); (x,y)
    """
    xbulls = x.get()
    ybulls = y.get()
    
    r = r.get() * 1852
    theta = theta.get()
    xtemp = r * math.cos(math.radians(theta)) 
    ytemp = r * math.sin(math.radians(theta)) 
    ytemp = int(ytemp)
    xtemp = int(xtemp)
    xt = xtemp + xbulls
    yt = ytemp + ybulls
    yt = int(yt)
    xt = int(xt)
    labelResult5.config(text=xt)
    labelResult6.config(text=yt)
    xtint = str(xt)
    ytint = str(yt)
    config_name = "logs\export_tgt_bra.txt"
    config_full_path = os.path.join(application_path, config_name)
    log_file = open(config_full_path, "w")
    log_file.write(xtint + "," + ytint)
    log_file.close()

    return x,y
rect = partial(rect, labelResult5, labelResult6, TR, TB, xbulls, ybulls)

def polar(labelResult7, labelResult8, x, y, xt, yt):
    """returns r, theta(degrees)
    """
    config_name = "logs\export_tgt_bra.txt"
    config_full_path = os.path.join(application_path, config_name)
    config_name1 = "Saved Games\DCS\Scripts\DCS_BRA\logs\export_self_bra.txt"
    config_full_path1 = os.path.join(os.path.expanduser('~'), config_name1)

    with open(config_full_path1) as f:
        str = f.readline().rstrip()
    chunks = str.split(',')
    x = int(chunks[0])
    y = int(chunks[1])
 
    
    with open(config_full_path) as f1:
        str = f1.readline().rstrip()
    chunkst = str.split(',')
    xt = int(chunkst[0])
    yt = int(chunkst[1])    
    R = ((xt - x) ** 2 + (yt - y) ** 2) ** .5
    R = R / 1852
    B = math.atan2((yt - y),(xt - x))    
    if B < 0 :
        B = B + 2 * math.pi
    
    B = B * 180 / math.pi
    
    R = int(R)
    B = int(B)
    labelResult7.config(text=B, bg="green", fg="black", font=(None, 15), height=1, width=4)
    labelResult8.config(text=R, bg="green", fg="black", font=(None, 15), height=1, width=4)

    return R,B
polar = partial(polar, labelResult7, labelResult8, x, y, xt, yt)



class Client:
    def connect(self):
     
        SERVER_ADDRESS = '127.0.0.1'
        SERVER_PORT = 31090
        s = socket.socket()
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((SERVER_ADDRESS, SERVER_PORT))
        s.listen(5)

        print("Listening on address %s. Kill server with Ctrl-C" %
              str((SERVER_ADDRESS, SERVER_PORT)))
        labelResult15.config(text="Connected on port 31090")
        

    #def receive(self):
        while True:
            c, addr = s.accept()
            print("\nConnection received from %s" % str(addr))
            labelResult15.config(text="Receiving data")
            
            while True:
                data = c.recv(2048)
                #time.sleep(10)
                if not data:
                    print("End of file from client. Resetting")
                    break
                    
                data = data.decode()
                data = data.split(",")
                x = data[0]
                y = data[1]
                Bearing = data[2]
                Range = data[3]

                #print('%s' % x)
                #print('%s' % data[1])
                #print('%s' % data[2])
                #print('%s' % data[3])

                labelResult1.config(text=x)
                labelResult2.config(text=y)  
                labelResult3.config(text=Bearing)  
                labelResult4.config(text=Range)  
                
            time.sleep(0.01)
            c.close()
    
c1 = Client()    

def connect():
    t1 = threading.Thread(target=c1.connect)
    t1.daemon = True # so this thread gets killed when tk stops
    t1.start()

def destroy():
    #if os.path.exists(os.path.join(os.path.expanduser('~'), "Saved Games\DCS\Scripts\DCS_BRA\export_self_bra.txt")):
    os.remove(os.path.join(os.path.expanduser('~'), "Saved Games\DCS\Scripts\DCS_BRA\logs\export_self_bra.txt"))
    os.remove(os.path.join(os.path.expanduser('~'), "Saved Games\DCS\Scripts\DCS_BRA\logs\BullsEyeRef.txt"))
     #if os.path.exists(os.path.join(application_path, "export_tgt_bra.txt")):
    os.remove(os.path.join(application_path, "logs\export_tgt_bra.txt"))   
    root.destroy()    
 

if __name__ == "__main__":

    b1.configure(command=connect)
    b2.configure(command=destroy)
    #b3.configure(command=rect)
    b4.configure(command=lambda:[bulls(), rect(), polar()])
    b5.configure(command=bulls)
    #command=lambda:[funcA(), funcB(), funcC()]
    #b2.configure(command=call_result)
    root.mainloop()

