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

from PyQt5.QtWidgets import *
from PyQt5.QtCore import (QSettings, QThread, pyqtSignal, pyqtSlot)

from vispy import app, visuals, scene

from main_ui import Ui_MainWindow
from settings_ui import Ui_Dialog as Ui_Settings

import numpy as np
import random
from colorsys import hsv_to_rgb
import pprint
import datetime

from functions import *
from listenUDP import listenUDP
from pingThread import pingThread
import vispyHelper

import csv
import socket


random.seed()

class AppWindow(QMainWindow):
	
	csv = None
	
	def __init__(self):
		super().__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		self.settings = QSettings("bexus", "imufusion")
		
		self.ip = getSettings(self.settings, 'ip', "172.16.18.171")
		self.port = getSettings(self.settings, 'port', 1234)
		logFile = getSettings(self.settings, 'logFile', "default")
		self.logFile = open("logs/{}_{}.txt".format(logFile, datetime.datetime.now().strftime('%m%d-%H%M%S')), "w")
		
		
		self.ui.labelAddress.setText("{}:{}".format(self.ip, self.port))
		self.ui.pushButton_reset.clicked.connect(self.reset_pressed)
		
		#self.ui.tableWidget.setColumnCount(4)
		#self.ui.tableWidget.setRowCount(4)
		#self.ui.tableWidget.setItem(0,1, QTableWidgetItem("TEXT"))
		
		self.udpServer = listenUDP(self.port)
		self.udpServer.newMsg.connect(self.onNewMsg)
		
		self.pingThread = pingThread(self.ip)
		self.pingThread.pong.connect(self.onPong)
		
		self.data3d = np.array([[0,0,0]], np.float32)
		
		self.view3D = vispyHelper.view3D(self.ui.openGLWidget)
		self.viewQuad = vispyHelper.viewQuad(self.ui.openGLWidgetQuad)

		
		self.udpServer.start()
		self.pingThread.start()
		
		self.timer = app.Timer()
		self.timer.connect(self.update)
		self.timer.start(0.1)
		
		self.show()
		
	def onNewMsg(self, data):
		self.ui.labelTestData.setText(pprint.pformat(data))
		
		if self.csv == None:
			self.csv = csv.DictWriter(self.logFile, data.keys())
			self.csv.writeheader()
			

		self.csv.writerow(data)
		
		rx, ry, rz =data["rot"]
		heading = data["mag_head"]
		
		if rz != 0:
			rx = np.arctan(ry / rz)
			ry = np.arctan(rx / rz)
		else:
			rx = np.arctan(0)
			ry = np.arctan(0)
		rz = 180 + heading
		
		rx *= 45
		ry *= -45
		
		rx += 90
		rz -= 90
		
		np.append(self.data3d, data["pos"])
		
		if self.ui.tabWidget.currentIndex() == 0:
			self.view3D.update(self.data3d, (rx, ry, rz))
		elif self.ui.tabWidget.currentIndex() == 1:
			self.viewQuad.update(self.data3d, (rx, ry, rz))
			
		self.ui.label_temp_adc_1.setText("{:.2g} °C".format(data["adc_temperature"]))
		self.ui.label_temp_cis_1.setText("{:.2g} °C".format(data["temperature_cis"]))
		self.ui.label_temp_mag_1.setText("{:.2g} °C".format(data["temperature_mag"]))
		self.ui.label_temp_mpu_1.setText("{:.2g} °C".format(data["temperature_mpu"]))
		
		self.ui.label_AcX.setText("{:g}".format(data["accel_raw"][0]))
		self.ui.label_AcY.setText("{:g}".format(data["accel_raw"][1]))
		self.ui.label_AcZ.setText("{:g}".format(data["accel_raw"][2]))
		self.ui.label_GyX.setText("{:g}".format(data["gyro_raw"][0]))
		self.ui.label_GyY.setText("{:g}".format(data["gyro_raw"][1]))
		self.ui.label_GyZ.setText("{:g}".format(data["gyro_raw"][2]))
		
		self.ui.label_MaX.setText("{:g}".format(data["mag_raw"][0]))
		self.ui.label_MaY.setText("{:g}".format(data["mag_raw"][1]))
		self.ui.label_MaZ.setText("{:g}".format(data["mag_raw"][2]))
		
		self.ui.label_pres_cis_1.setText("{:.1g} Pa".format(data["pressure_cis"]))
		#self.ui.label_pres_i2c_1.setText("{:.1g} Pa".format(data["pressure_spi"]))	
		
		self.ui.label_lat_1.setText("{:.5g}".format(data["latitude"]))
		self.ui.label_lon_1.setText("{:.5g}".format(data["longitude"]))
		self.ui.label_alt_1.setText("{:.2g} m".format(data["altitude"]))
		try:
			dt = datetime.datetime.fromtimestamp(data["time"] / 1000)
			self.ui.label_date_1.setText(dt.strftime('%d.%m.%Y'))
			self.ui.label_time_1.setText(dt.strftime('%H:%M:%S'))
		except(OSError):
			pass
		self.ui.label_hdop_1.setText("{:g}".format(data["hdop"]))
		
	def update(self, ev):
		#reset
		value = self.ui.progressBar_reset.value()
		if value > 0:
			value -= 1
			self.ui.progressBar_reset.setValue(value)
			
		return
	
	def reset_pressed(self):
		value = self.ui.progressBar_reset.value()
		value += 10
		if value > 100:
			value = 0
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			sock.sendto(bytes("RESET!!", "utf-8"), (self.ip, 65100))
			
		self.ui.progressBar_reset.setValue(value)
	
	def onPong(self, t):
		if t != -1:
			self.ui.labelLatency.setText("{:.1f}ms".format(t*1000))
			self.ui.labelLink.setText("Online")
			self.ui.labelLink.setStyleSheet("color:green")
		else:
			self.ui.labelLatency.setText("")
			self.ui.labelLink.setText("Offline")
			self.ui.labelLink.setStyleSheet("color:red")

	@pyqtSlot(bool)
	def on_actionSettings_triggered(self, triggered):
		self.settings

		d = QDialog()
		d.ui = Ui_Settings()
		d.ui.setupUi(d)
		d.ui.lineEditIP.setText(self.ip)
		d.ui.lineEditPort.setText(str(self.port))
		
		if d.exec_():
			self.ip = d.ui.lineEditIP.text()
			self.port = safe_cast(d.ui.lineEditPort.text(), int, 1234)
			logFile = d.ui.lineEditLogFile.text()
			self.settings.setValue('ip', self.ip)
			self.settings.setValue('port', self.port)
			self.settings.setValue('logFile', logFile)
			
			self.logFile = open("logs/{}_{}.txt".format(logFile, datetime.datetime.now().strftime('%m%d-%H%M%S')), "w")
			self.csv = None
			
			self.pingThread.changeIP(self.ip)
			self.udpServer.stop()
			self.udpServer = listenUDP(self.port)
			self.udpServer.newMsg.connect(self.onNewMsg)
			self.udpServer.start()
			
			self.ui.labelAddress.setText("{}:{}".format(self.ip, self.port))

			# this writes the settings to storage
			self.settings.sync()
	
	def on_actionFollow_triggered(self, triggered):
		print(triggered)