"""

Author: Obrtac Tomas (obrtac.tomas@gmail.com)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

import REST_api as Ra
from PySide import QtGui
import Showing_hiding_files as shgui_op
import Set_text_to_inputs as set_text
#Vytvaranie noveho zariadenia
def Create_new_device(self):
    if self.option_list.currentItem().recognizing_value == 22: #Pre pripad linku
        successful = Ra.create_new_link(is_button_checked(self,), #Zavolame si REST api ktora to vytvori a vlozime do nej hodnoty
                           self.Set_Power_input.currentIndex(),
                           self.AppSKey_input.text(),
                           self.NwksKEY_input.text(),
                           self.Application_input.currentText(),
                           self.Region_input.currentText(),
                           self.Devaddr_input.text(),
                           self.FCnt_Check_input.currentIndex(),
                           self.Set_data_rate_input.currentIndex(),
                           self.name,
                           self.password)
        if successful == 1: #Ak bolo uspesne tak OK hlaska
            self.link_addreses.append(self.Devaddr_input.text()) #Prihodime adresu medzi zoznam a vlozime ju do widgetu
            Add_address_to_link_list(self, self.Devaddr_input.text())
            set_text.delete_values_in_links(self) #Vymazeme hodnoty v poliach
        return

    if self.option_list.currentItem().recognizing_value == 32: #Pre pripad device
        successful = Ra.create_new_device(is_button_checked(self), #Zavolame si REST api ktora to vytvori a vlozime do nej hodnoty
                             self.Set_Power_input.currentIndex(),
                             self.Can_joinD_input.currentText(),
                             self.AppKey_input.text(),
                             self.AppEUI_input.text(),
                             self.Application_input.currentText(),
                             self.Region_input.currentText(),
                             self.DevEUI_input.text(),
                             self.Set_data_rate_input.currentIndex(),
                             self.name,
                             self.password)
        self.devices_addreses.append(self.Devaddr_input.text()) #Prihodime adresu medzi zoznam a vlozime ju do widgetu
        Add_address_to_devices_list(self,self.DevEUI_input.text())
        set_text.delete_values_in_devices(self) #Vymazeme hodnoty v poliach
        return

    if self.option_list.currentItem().recognizing_value == 41: #Pre pripad gateway-e
        successful = Ra.create_new_gateway(self.MAC_input.text(), #Zavolame si REST api ktora to vytvori a vlozime do nej hodnoty
                              self.TX_Channel_input.text(),
                              self.NetID_input.text(),
                              self.name,
                              self.password)
        self.gateway_addresses.append(self.MAC_input.text())
        Add_address_to_gateway_list(self, self.MAC_input.text()) #Prihodime adresu medzi zoznam a vlozime ju do widgetu
        set_text.delete_values_in_devices(self) #Vymazeme hodnoty v poliach
        return

#Editovanie existujucich zariadeni
def Edit_existing_device(self):
    if self.option_list.currentItem().recognizing_value == 33: # PRe device, zavolame REST api a vlozime potrebne hodnoty
        Ra.edit_existing_device(is_button_checked(self),
                             self.Set_Power_input.currentIndex(),
                             self.Can_joinD_input.currentText(),
                             self.AppKey_input.text(),
                             self.AppEUI_input.text(),
                             self.Application_input.currentText(),
                             self.Region_input.currentText(),
                             self.DevEUI_input.text(),
                             self.Set_data_rate_input.currentIndex(),
                             self.name,
                             self.password)
        return
    if self.option_list.currentItem().recognizing_value == 23: # PRe links, zavolame REST api a vlozime potrebne hodnoty
        Ra.edit_existing_link(is_button_checked(self),
                             self.Set_Power_input.currentIndex(),
                             self.AppSKey_input.text(),
                             self.NwksKEY_input.text(),
                             self.Application_input.currentText(),
                             self.Region_input.currentText(),
                             self.Devaddr_input.text(),
                             self.FCnt_Check_input.currentIndex(),
                             self.Set_data_rate_input.currentIndex(),
                             self.name,
                             self.password)

    if self.option_list.currentItem().recognizing_value == 42: # PRe gateway, zavolame REST api a vlozime potrebne hodnoty
        Ra.edit_existing_gateway(self.MAC_input.text(),
                                    self.NetID_input.text(),
                                    self.TX_Channel_input.text(),
                                    self.name,
                                    self.password)
    return

#Vkladanie hodnot do zoznamu s deveui
def Add_address_to_devices_list(self,address):
    Linklayout = Links(address)
    self.qlistwidgetitem.append(QtGui.QListWidgetItem(self.devices_list))
    self.qlistwidgetitem[-1].setSizeHint(Linklayout.sizeHint())
    self.devices_list.addItem(self.qlistwidgetitem[-1])
    self.devices_list.setItemWidget(self.qlistwidgetitem[-1], Linklayout)

#Vkladanie hodnot do zoznamu s devaddr
def Add_address_to_link_list(self,address):
    Linklayout = Links(address)
    self.qlistwidgetitem.append(QtGui.QListWidgetItem(self.links_list))
    self.qlistwidgetitem[-1].setSizeHint(Linklayout.sizeHint())
    self.links_list.addItem(self.qlistwidgetitem[-1])
    self.links_list.setItemWidget(self.qlistwidgetitem[-1], Linklayout)

#Vkladanie hodnot do zoznamu s DEVEUI
def Add_address_to_gateway_list(self,address):
    Linklayout = Links(address)
    self.qlistwidgetitem.append(QtGui.QListWidgetItem(self.gateway_list))
    self.qlistwidgetitem[-1].setSizeHint(Linklayout.sizeHint())
    self.gateway_list.addItem(self.qlistwidgetitem[-1])
    self.gateway_list.setItemWidget(self.qlistwidgetitem[-1], Linklayout)

#Vkladanie hodnot do zoznamu s datumami
def Add_date_to_dates_list(self,date):
    Linklayout = Links(date)
    self.qlistwidgetitem.append(QtGui.QListWidgetItem(self.Dates_list))
    self.qlistwidgetitem[-1].setSizeHint(Linklayout.sizeHint())
    self.Dates_list.addItem(self.qlistwidgetitem[-1])
    self.Dates_list.setItemWidget(self.qlistwidgetitem[-1], Linklayout)

#Back button obstaravanie
def Back_button(self):
    #Riesim tu jednotlive stavy, v podstate sa nejedna o niz zlozite, zasa nieco skryje, zobrazi
    if self.option_list.currentItem().recognizing_value == 33:  #Edit devices
        shgui_op.Create_new_device_hide(self)
        shgui_op.Edit_button_hide(self)
        shgui_op.List_of_devices_show(self)
        set_text.uncheck_buttons(self)
        return

    if self.option_list.currentItem().recognizing_value == 23: #Edit Links
        shgui_op.Create_new_link_hide(self)
        shgui_op.Edit_button_hide(self)
        shgui_op.List_of_devaddr_show(self)
        set_text.uncheck_buttons(self)
        return

    if self.option_list.currentItem().recognizing_value == 42: #Edit Gateways
        shgui_op.Create_new_gateway_hide(self)
        shgui_op.Edit_button_hide(self)
        shgui_op.List_of_gateways_show(self)
        return

    if self.option_list.currentItem().recognizing_value == 36: #Pozeranie Linkov zariadeni
        set_text.uncheck_buttons(self)
        shgui_op.Create_new_link_hide(self)
        shgui_op.Back_button_for_devices_hide(self)
        set_text.delete_values_in_links(self)
        shgui_op.List_of_devices_show(self)

#Mazanie, opat sa pozrie kde je a vyhodnoti ktore REST API ma spustit
def Delete_device(self):
    if self.option_list.currentItem().recognizing_value == 34:
        if self.devices_list.currentRow() != -1:
            Answer = QtGui.QMessageBox.question(None, "Information",
                                             "Do you really want to delete this device",
                                             QtGui.QMessageBox.Yes,
                                             QtGui.QMessageBox.No)
            if Answer == 16384:
                index = self.devices_list.currentRow()
                self.devices_list.takeItem(index)
                Ra.delete_device(self.devices_addreses[index],self.name,self.password)
                self.devices_addreses.remove(self.devices_addreses[index])
                QtGui.QMessageBox.question(None,"Message","Device was deleted",QtGui.QMessageBox.Ok)
        else:
            QtGui.QMessageBox.question(None, "Message", "Select device", QtGui.QMessageBox.Ok)
        return

    if self.option_list.currentItem().recognizing_value == 24:
        if self.links_list.currentRow() != -1:
            Answer = QtGui.QMessageBox.question(None, "Information",
                                             "Do you really want to delete this device",
                                             QtGui.QMessageBox.Yes,
                                             QtGui.QMessageBox.No)
            if Answer == 16384:
                index = self.links_list.currentRow()
                self.links_list.takeItem(index)
                Ra.delete_link(self.link_addreses[index])
                self.link_addreses.remove(self.link_addreses[index])
                QtGui.QMessageBox.question(None,"Message","Device was deleted",QtGui.QMessageBox.Ok)
        else:
            QtGui.QMessageBox.question(None, "Message", "Select device", QtGui.QMessageBox.Ok)
        return

    if self.option_list.currentItem().recognizing_value == 43:
        if self.gateway_list.currentRow() != -1:
            Answer = QtGui.QMessageBox.question(None, "Information",
                                             "Do you really want to delete this gateway",
                                             QtGui.QMessageBox.Yes,
                                             QtGui.QMessageBox.No)
            if Answer == 16384:
                index = self.gateway_list.currentRow()
                self.gateway_list.takeItem(index)
                Ra.delete_link(self.gateway_addresses[index],self.name,self.password)
                self.gateway_addresses.remove(self.gateway_addresses[index])
                QtGui.QMessageBox.question(None,"Message","Gateway was deleted",QtGui.QMessageBox.Ok)
        else:
            QtGui.QMessageBox.question(None, "Message", "Select device", QtGui.QMessageBox.Ok)
        return

#Vkladanie hodnot do Dates list
def Put_values_to_Dates_list(self,dev_addr):
        data = Ra.read_data(dev_addr,self.name,self.password)
        #self.devices_options = numpy.zeros(shape = (1,length_of_adress))
        self.qlistwidgetitem = []
        if data.datetime :
            for i in range(len(data.datetime)):
                #adeni pripojenych
                Linklayout = Links(data.datetime[i])
                self.qlistwidgetitem.append(QtGui.QListWidgetItem(self.Dates_list))
                self.qlistwidgetitem[i].setSizeHint(Linklayout.sizeHint())
                self.Dates_list.addItem(self.qlistwidgetitem[i])
                self.Dates_list.setItemWidget(self.qlistwidgetitem[i],Linklayout)
        return data

#Vratenie sa naspat do zoznamu devaddr, pouzivame pri zobrazovani grafov
def back_to_list_of_devaddr(self):
    shgui_op.TabWidget_for_graphs_hide(self)
    shgui_op.Back_graph_button_hide(self)
    shgui_op.List_of_devaddr_show(self)
    shgui_op.List_of_dates_hide(self)
    self.Dates_list.clear()

#Vkladanie hodnot do grafov
def Put_values_to_graph(self,data_from_device,current_index):
    #self.Pressure_plot.plot_values.plot(data_from_device.hour[current_index],data_from_device.data_t[current_index])
    self.Temperature_plot.actualize_values(data_from_device.hour[current_index],
                                               data_from_device.data_t[current_index],"T [C]")
    self.Pressure_plot.actualize_values(data_from_device.hour[current_index],
                                               data_from_device.data_p[current_index],"P [hPa]")
    self.Humidity_plot.actualize_values(data_from_device.hour[current_index],
                                               data_from_device.data_h[current_index],"X [%]")
    self.Light_plot.actualize_values(data_from_device.hour[current_index],
                                        data_from_device.data_l[current_index], "Mv [lux]")
    self.TabWidget_for_graphs.show()

#Aktualizovanie grafo, list of devaddr a datumov
def Refresh_button_actions(self):
    #Pre pripad ze sme este nevybrali devaddr
    if not self.Back_graphs_button.isVisible():
        previous_list = self.link_addreses
        self.link_addreses = Ra.list_of_devaddr()
        difference = list(set(self.link_addreses) - set(previous_list))
        #Zistime ci nieco pribudlo ak hej tak to pridame do listu
        if len(difference) > 0:
            for i in range(len(difference)):
                Add_address_to_link_list(self,difference[i])
        return
    #Pre pripad ze aktualizujeme datumy
    if not self.TabWidget_for_graphs.isVisible():
        data = self.data_from_device
        self.Dates_list.clear()
        self.data_from_device = Put_values_to_Dates_list(self, self.link_addreses[self.links_list.currentRow()])
        return
    #Konecna aktualizacia grafu
    self.data_from_device =  Ra.read_data(self.link_addreses[self.links_list.currentRow()],self.name,self.password)
    Put_values_to_graph(self,self.data_from_device,self.Dates_list.currentRow())
    return

#Buton je zaskrtnuty
def is_button_checked(self):
    name = "Check_box_"
    check = ""
    start = 0
    result = ""
    for j in range(1, 16):
        exec ("%s = self.%s%d.isChecked()" % ("check",name, j))
        if check == 1:
            if start == 0:
               start = 1
               result += str(j) +"-"
        else:
            if start == 1:
                result += str(j-1) +","
                start = 0
    result = result[:-1]
    return result

#Triedu ktoru som tu musel vlozit aby som dokazal vkladat devaddr,deveui ...
class Links(QtGui.QWidget): #Trieda pre nastavenie dizajnu moznosti v devicoch

    def __init__(self, devaddr,parent = None):
        super(Links,self).__init__(parent)
        self.devaddr = devaddr
        self.BoxLayout = QtGui.QVBoxLayout()
        self.textLabel = QtGui.QLabel()
        self.BoxLayout.addWidget(self.textLabel)
        self.textLabel.setStyleSheet("color: black;"
                        "selection-color: white;"
                        "selection-background-color: red;")
        self.textLabel.setText(devaddr)
        self.textLabel.setFont(QtGui.QFont("Calibri", 8))
        self.setLayout(self.BoxLayout)