#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 14:30:51 2018

@author: jan
"""

import sys
import time
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer

import socket
import os
import json

import queue

from main_window import Ui_MainWindow

from channelInfoClass import channelInfo

import globalvars
######################################################################
#TCP/IP
HOST = '' #Symbolic name
PORT = 2000

######################################################################

#Function to convert byte string to int/float
def str2num(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return 0

class ApplicationWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        QMainWindow.__init__(self)
        self.setupUi(self)

        self.tcpqueue = queue.Queue(100)

        self.channel = [0]

        temp_field   = [self.temp_ch0]
        out_field    = [self.out_ch0]
        enable_field = [self.enable_ch0]

        #Open json settings file defined in globalvars
        self.loadSettingsFile(globalvars.settingsFile)

        for ch in range(len(self.channel)):
            self.channel[ch] = channelInfo(ch,temp_field[ch],out_field[ch],enable_field[ch], ch, self.tabWidget ,self)
            self.channel[ch].setEnabled(False)

        self.layout_ch0.addWidget(self.channel[0].widget_obj)
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_0),globalvars.settings["ch0"]["name"])
        #self.layout_ch1.addWidget(self.channel[1].widget_obj)
        #self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_1),globalvars.settings["ch1"]["name"])
        #self.layout_ch2.addWidget(self.channel[2].widget_obj)
        #self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),globalvars.settings["ch2"]["name"])
        #self.layout_ch3.addWidget(self.channel[3].widget_obj)
        #self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3),globalvars.settings["ch3"]["name"])

        self.ip_address.setText(globalvars.settings["defaultIP"])
        self.portField.setText(str(globalvars.settings["defaultPort"]))

        #Connect radio buttons to functions
        self.remoteRadioButton.toggled.connect(lambda:self.settingsSelection(self.remoteRadioButton))
        self.localRadioButton.toggled.connect(lambda:self.settingsSelection(self.localRadioButton))

        # Close event to save settings
        app.aboutToQuit.connect(self.closeEvent)
        # Button functions
        self.connectButton.clicked.connect(self.connectButtonChange)

        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.refresh)

    def connectButtonChange(self):
        if self.connectButton.isChecked():
            #Open connection to server
            self.sock = socket.socket()
            self.address = self.ip_address.text()
            self.port = self.portField.text()

            try:
                self.sock.connect((self.address,int(self.port)))
            except Exception as e:
                print("something's wrong with %s:%s. Exception is %s" % (self.address, self.port, e))
                globalvars.conStatus = False
                self.connectButton.setChecked(False)
                return

            try:
                data_recv = self.sock.recv(1024)
                print(data_recv.decode())
            except OSError:
                globalvars.conStatus = False
                self.connectButton.setChecked(False)
                print('\nSocket broken')
                return

            globalvars.conStatus = True
            globalvars.sock = self.sock
            print("connect to "+ self.address)

            for ch in range(len(self.channel)):
                self.channel[ch].loadSettings()

            self.refresh_timer.start(500)

        else:
            globalvars.conStatus = False
            self.refresh_timer.stop()
            time.sleep(0.1)
            print("disconnect from "+ self.address)
            self.sock.close()

        for ch in range(len(self.channel)):
            self.channel[ch].setEnabled(globalvars.conStatus)

        self.remoteRadioButton.setEnabled(not globalvars.conStatus)
        self.localRadioButton.setEnabled(not globalvars.conStatus)

    def refresh(self):
        for ch in range(len(self.channel)):
            pass
            self.channel[ch].update()

    def settingsSelection(self,b):
      if b.objectName() == "remoteRadioButton":
         if b.isChecked() == True:
            globalvars.remoteSettings = True
         else:
            globalvars.remoteSettings = False

      if b.objectName() == "localRadioButton":
         if b.isChecked() == True:
            globalvars.remoteSettings = False
         else:
            globalvars.remoteSettings = True

    def loadSettingsFile(self,path):
        with open(path) as c:
            globalvars.settings = json.load(c)

    def closeEvent(self, event):
        globalvars.conStatus = False

        print("Saving settings... ")
        with open(globalvars.settingsFile, 'w') as f:
            json.dump(globalvars.settings, f, ensure_ascii=True)
        print('done.')
        sys.exit(0)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = ApplicationWindow()
    main.setWindowTitle("Tempertur-Controller V1")
    main.show()
    app.exec_()
