'''
/** Original work Copyright 2024 damiano IU3QGD
 * https://to-be-defined
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.

 * Addition to the licence: NO company with more than 50employees can use this SW and you are NOT entitled to store this software 
 * on ANY storage that in some way attempts to monetize it (eg: github)
 * corporations and banks are too rich and too powerful, they MUST be split and ALL the money given back to the state

'''
# -------------------------------------------------------------------------
# There is only ONE poll, this is a GUI and if there is something to send it should be set to the poll

from __future__ import annotations

from tkinter import IntVar

from app_config import AppConfig, ConfigSavable
from glob_gui import JtkWinToplevel, LogPanel, JtkPanelGrid, TV_Entry,\
    GUI_hide_show_window, TV_EntryFrequency_MHz_1x, TV_EntryFrequency_kHz_1x,\
    JtkPanelPackLeft, JtkLabel, JtkPanelPackTop 
from glob_ippqs import Qsk5_res_Spectrum
from ipp_parser import Qsk5_req_spectrum_scan, Qsk5_req_scan_loud
import qpystat
import tkinter.ttk as ttk


class SpectrumGui (ConfigSavable,GUI_hide_show_window):

    # ----------------------------------------------------------------
    def __init__(self, stat : qpystat.Qpystat):
        self.stat = stat
        
        self.stat.appconfig.addMyselfToSavables(self)

        self._toplevel = JtkWinToplevel("Spectrum window")
        
        aframe=JtkPanelPackTop(self._toplevel)     
        
        aframe.addItem(self._newScanSpectrumPanel(aframe))
        aframe.addItem(self._newScanLoudestPanel(aframe))
        
        self._spectrum_log = LogPanel(aframe,"Spectrum Log")
        aframe.addItem(self._spectrum_log,fill='both',expand=True)
        
        aframe.pack(fill='both',expand=True)
        
        self.GUI_hide_window()
        
        self._println("SpectrumGui init complete")

    # -------------------------------------------------------------------
    # prints something on the application log
    def _println(self, msg):
        self._spectrum_log.println(msg)    
        
    # -------------------------------------------------------------------
    # Shows the values, now
    def showSpectrum_res(self, chunk : Qsk5_res_Spectrum):
        
        cur_F = chunk.start_freq_1x;
        step_F = chunk.step_freq_1x;
        
        self._println("start F_1x "+str(cur_F))
                
        s_count = chunk.samples_count;
        
        for index in range(s_count):
            rssi_v = chunk.samples[index]
            self._println("["+str(index)+"] F="+str(cur_F)+" rssi="+str(rssi_v))

            # increment after display
            cur_F = cur_F + step_F
            
        
    # --------------------------------------------------------------------
    # show a window that has been hidden using the withdraw method
    def GUI_show_window(self):
        self._toplevel.deiconify()    

    # --------------------------------------------------------------------
    # hide completely a window
    def GUI_hide_window(self):
        self._toplevel.withdraw()    
    
    # -------------------------------------------------------------------------------
    # make a new frame and put input line in it
    def _newScanLoudestPanel(self, parent):

        panel=JtkPanelPackLeft(parent, borderwidth=3, relief='groove')

        self.scanLoudFrequency = TV_EntryFrequency_MHz_1x(panel,value=14400000)
        self.scanTime_cs = IntVar(panel,value=50)
        
        panel.addItem(JtkLabel(panel,"Center frequency "))
        panel.addItem(self.scanLoudFrequency)
        panel.addItem(JtkLabel(panel,"  Scan Time (cs): "))
        panel.addItem(TV_Entry(panel, self.scanTime_cs, width=5))
        panel.addItem(ttk.Button(panel,text="SCAN loudest F" , command=self._reqScanLoud ))
        
        return panel

    # --------------------------------------------------------------------------------------
    def _reqScanLoud(self):
        try:
            a_f = int(self.scanLoudFrequency.get_value())
        except Exception as _exc:
            a_f=44611000
            
        try:
            a_t = int(self.scanTime_cs.get())
        except Exception as _exc:
            a_t=20

        cmd = Qsk5_req_scan_loud(a_t,a_f)
        self.stat.qconnect.queuePut(cmd)
        
        self.stat.app_println("request="+str(cmd))

    
    
    # -------------------------------------------------------------------------------
    # Example of how to use grid layout
    def _newScanSpectrumPanel(self,parent_panel : ttk.Frame):
        
        gridpanel = JtkPanelGrid(parent_panel, borderwidth=3, relief='groove', padding='3px')

        self._edit_start_frequency = TV_EntryFrequency_MHz_1x(gridpanel,value=44600000)
        self._edit_step_F_1x = TV_EntryFrequency_kHz_1x(gridpanel,value=10000)
        self._edit_samples_count = IntVar(gridpanel,value=10)
        self._edit_stime_cs = IntVar(gridpanel,value=2)

#        panel.grid_rowconfigure(0, weight = 1) 
#        panel.grid_columnconfigure(1, weight = 1)
        
        gridpanel.addItem(JtkLabel(gridpanel,"Start Frequency "))
        gridpanel.addItem(self._edit_start_frequency)

        gridpanel.addItem(JtkLabel(gridpanel,"Step Frequency "))
        gridpanel.addItem(self._edit_step_F_1x)

        gridpanel.addItem(ttk.Button(gridpanel,text="Scan Spectrum" , command=self._clicScanSpectrum ),rowspan=2)
        
        gridpanel.nextRow()

        gridpanel.addItem(JtkLabel(gridpanel,"Samples Count"))
        gridpanel.addItem(TV_Entry(gridpanel, self._edit_samples_count,width=3))

        gridpanel.addItem(JtkLabel(gridpanel,"Samples Time (cs)"))
        gridpanel.addItem(TV_Entry(gridpanel, self._edit_stime_cs,width=3))

        return gridpanel
    
    # --------------------------------------------------------------------------------------
    def _clicScanSpectrum(self):
        cmd = Qsk5_req_spectrum_scan(self._edit_start_frequency.get_value(), self._edit_step_F_1x.get_value(), self._edit_samples_count.get(), self._edit_stime_cs.get())
        self._println('_clicScanSpectrum: '+str(cmd))
        self.stat.qconnect.queuePut(cmd)

    # -------------------------------------------------------------------
    # implement the config savable
    def appImportConfig(self, cfg : AppConfig ):
        adict = cfg.getDictValue("spectrum_cfg", {})
        
        try:
            self._toplevel.setGeometry(adict['gui_cfg'])
        except Exception as _exc :
            self._println("spectrum.appImportConfig"+str(_exc))            

    # -------------------------------------------------------------------
    # implement the config savable
    def appSaveConfig(self, cfg : AppConfig ):
        adict = dict()

        adict['gui_cfg'] = self._toplevel.getGeometry()

        cfg.setDictValue("spectrum_cfg", adict )        
        
        
        
            
    
    

        
        

