#!/usr/bin/python
#======================================================================
#
# Project	 : hpp_IOStressTest
# File 		 : Libs/IOST_Testcase/IOST_SaveConfig.py
# Date		 : Dec 14, 2016
# Author	 : HuuHoang Nguyen
# Contact	 : hhnguyen@apm.com
#            : hoangnh.hpp@gmail.com
# License    : MIT License
# Copyright  : 2016
# Description: The hpp_IOStressTest is under the MIT License, a copy of license which may be found in LICENSE
#
#======================================================================

import io
import os
import sys
import time

from IOST_Basic             import *
from IOST_Config            import *
from IOST_Testcase          import *

import gtk
import gtk.glade
import gobject

#======================================================================
try:
    IOST_DBG_EN
    if IOST_DBG_EN:
        IOST_SaveConfig_DebugEnable =0
        IOST_SaveConfig_DebugLevel  =IOST_DBG_L01
    else:
        IOST_SaveConfig_DebugEnable =0
        IOST_SaveConfig_DebugLevel  =IOST_DBG_L01
except:
    IOST_DBG_EN = False
    IOST_SaveConfig_DebugEnable =0
    IOST_SaveConfig_DebugLevel  =IOST_DBG_L01

#======================================================================
class IOST_SaveConfig():
    """
    """
    #----------------------------------------------------------------------
    def __init__(self, glade_filename, window_name="", object_name="", builder=None):
        ""
        self.IOST_SaveConfig_WindowName = window_name
        self.IOST_SaveConfig_ObjectName = object_name
        
        if not builder:
            self.IOST_SaveConfig_Builder = gtk.Builder()
            self.IOST_SaveConfig_Builder.add_from_file(glade_filename)
            self.IOST_SaveConfig_Builder.connect_signals(self)
        else:
            self.IOST_SaveConfig_Builder = builder
            self.IOST_SaveConfig_Builder.connect_signals(self)

    #----------------------------------------------------------------------
    def SaveConfig_Get_Objs(self, window_name):
        ""
        self.CreateObjsDictFromDict(window_name, self.IOST_Objs[window_name], self.IOST_SaveConfig_Builder, 0)
        self.IOST_Objs[window_name][self.IOST_SaveConfig_ObjectName].set_keep_above(True)
        self.SaveConfig_Init_Objs()  

    #----------------------------------------------------------------------
    def SaveConfig_Init_Objs(self):
        self.SaveConfig_Set_StationInfoPath_Obj()
        self.SaveConfig_Set_StationInfoSetup_Obj()
        self.SaveConfig_Set_TestcasesPath_Obj()
        self.SaveConfig_Set_TestcasesSetup_Obj()
        self.SaveConfig_StationInfoPath = self.IOST_Data['IOST_RunPath']+'/StationInfo.json'
        self.SaveConfig_TestcasesPath    = self.IOST_Data['IOST_RunPath']+'/Testcases.json'
        self.SaveConfig_StationInfo_SaveEnable = False
        self.SaveConfig_Testcase_SaveEnable    = False
        self.SaveConfig_Testcase_IP_IsDisableb = False
        
        
        
    #----------------------------------------------------------------------
    def SaveConfig_Show(self):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName][self.IOST_SaveConfig_ObjectName].show()
    
    #----------------------------------------------------------------------
    # def SaveConfig_Run(self):
    #     self.IOST_Objs[self.IOST_SaveConfig_WindowName][self.IOST_SaveConfig_ObjectName].run()
    
    #----------------------------------------------------------------------
    def SaveConfig_Hide(self):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName][self.IOST_SaveConfig_ObjectName].hide()
    
    #----------------------------------------------------------------------
    def SaveConfig_Destroy(self):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName][self.IOST_SaveConfig_ObjectName].destroy()

    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_Skylark_delete_event(self, object, event, data=None):
        ""
        self.SaveConfig_Hide()
        return True        
    
    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_Skylark_destroy_event(self, object, event, data=None):
        ""
        self.SaveConfig_Hide()
        return True

    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_StationInfoEnable_CB_toggled(self, object, data=None):
        ""
        res = object.get_active()
        if res:
            path = self.SaveConfig_StationInfoPath
        else:
            path=''

        iost_print(IOST_SaveConfig_DebugLevel, path, "StationInfoEnable_CB -> The path is :")

        self.SaveConfig_Set_StationInfoPath_Obj(res, path)
        self.SaveConfig_Set_StationInfoSetup_Obj(res)
        self.SaveConfig_StationInfo_SaveEnable = res
        
    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_TestcasesEnable_CB_toggled(self, object, data=None):
        ""        
        res = object.get_active()
        if res:
            path = self.SaveConfig_TestcasesPath
        else:
            path=''

        iost_print(IOST_SaveConfig_DebugLevel, path, "TestcasesEnable_CB -> The path is :")
        
        self.SaveConfig_Set_TestcasesPath_Obj(res, path)
        self.SaveConfig_Set_TestcasesSetup_Obj(res)
        self.SaveConfig_Testcase_SaveEnable = res

    def on_IOST_SaveConfig_SaveTestcases_OfIPDisable_CB_toggled(self, object, data=None):
        ""
        res = object.get_active()
        self.SaveConfig_Testcase_IP_IsDisableb = res
    
    #----------------------------------------------------------------------
    def SaveConfig_Set_StationInfoPath_Obj(self, sensitive=False, path=""):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName]['_StationInfoPath_TE'].set_sensitive(sensitive)
        self.IOST_Objs[self.IOST_SaveConfig_WindowName]['_StationInfoPath_TE'].set_text(path)

    #----------------------------------------------------------------------
    def SaveConfig_Set_StationInfoSetup_Obj(self, sensitive=False):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName]['_StationInfoSetup_B'].set_sensitive(sensitive)
    
    #----------------------------------------------------------------------
    def SaveConfig_Set_TestcasesPath_Obj(self, sensitive=False, path=""):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName]['_TestcasesPath_TE'].set_sensitive(sensitive)
        self.IOST_Objs[self.IOST_SaveConfig_WindowName]['_TestcasesPath_TE'].set_text(path)

    #----------------------------------------------------------------------
    def SaveConfig_Set_TestcasesSetup_Obj(self, sensitive=False):
        self.IOST_Objs[self.IOST_SaveConfig_WindowName]['_TestcasesSetup_B'].set_sensitive(sensitive)

    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_StationInfoSetup_B_clicked(self, object, data=None):
        ""
        text = "Save configure file to < Station Info >"
        self.SaveConfig_StationInfoPath = self.SaveConfig_SaveDialog(self.SaveConfig_StationInfoPath, text)
        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_StationInfoPath, "self.SaveConfig_StationInfoPath" )
        self.SaveConfig_Set_StationInfoPath_Obj(True, self.SaveConfig_StationInfoPath)

    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_TestcasesSetup_B_clicked(self, object, data=None):
        ""
        text = "Save configure file to < Testcases >"
        self.SaveConfig_TestcasesPath = self.SaveConfig_SaveDialog(self.SaveConfig_TestcasesPath, text)
        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_TestcasesPath, "self.SaveConfig_TestcasesPath")
        self.SaveConfig_Set_TestcasesPath_Obj(True, self.SaveConfig_TestcasesPath)
    
    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_Cancel_B_clicked(self,object, data=None):
        ""
        self.SaveConfig_Hide()
        return True

    #----------------------------------------------------------------------
    def on_IOST_SaveConfig_Save_B_clicked(self, object, data=None):
        """
        self.SaveConfig_StationInfoPath = self.IOST_Data['IOST_RunPath']+'/StationInfo.json'
        self.SaveConfig_TestcasesPath    = self.IOST_Data['IOST_RunPath']+'/Testcases.json'
        self.SaveConfig_StationInfo_SaveEnable = False
        self.SaveConfig_Testcase_SaveEnable    = False
        """

        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_StationInfoPath,        "self.SaveConfig_StationInfoPath :")
        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_StationInfo_SaveEnable, "self.SaveConfig_StationInfo_SaveEnable :")
        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_TestcasesPath,          "self.SaveConfig_TestcasesPath :")
        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_Testcase_SaveEnable,    "self.SaveConfig_Testcase_SaveEnable :")
        iost_print(IOST_SaveConfig_DebugLevel, self.SaveConfig_Testcase_IP_IsDisableb, "self.SaveConfig_Testcase_IP_IsDisableb :")
        
        self.save_cfg = IOST_Config()
        """
        'self.save_cfg.IOST_Data' will store Testcases
        'self.save_cfg.IOST_Objs' will store StationInfo
        """

        # Begin process to StationInfo
        self.save_cfg.IOST_Objs.update({"StationInfo": self.IOST_Data["StationInfo"]})

        # Begin process to Testcase
        ip_checked={}

        #init ip_check variable 
        for ip in self.IOST_Data['ObjectUpdate']:            
            if ip == "AutoMail": 
                 continue

            if ip_checked.has_key(ip[:-1]):
                continue
            else:
                ip_checked.update({ ip[:-1]: False } )
        pprint (ip_checked)

        #
        for ip in self.IOST_Data['ObjectUpdate']:
            #If ip is autoMail, ignore it
            if ip == "AutoMail": 
                continue

            #If ip was checked, ignore it
            if ip_checked[ip[:-1]]:
                continue

            # if check button 'Save the testcases of IP which have disabed' : Enable 
            if self.SaveConfig_Testcase_IP_IsDisableb:
                # print ip, ' : ', self.IOST_Data[ip[:-1]+'_PortNum']
                for ip_port in range(0, self.IOST_Data[ip[:-1]+'_PortNum']):
                    if len( self.IOST_Data[ip[:-1]+str(ip_port)] ) <= 1:
                        continue
                    else:
                        if not ip_checked[ip[:-1]]:
                            ip_checked[ip[:-1]] = True
                            self.save_cfg.IOST_Data.update( { ip[:-1] : self.IOST_Data[ip[:-1]] } )
                             
                        self.save_cfg.IOST_Data.update( { ip[:-1]+str(ip_port) : self.IOST_Data[ip[:-1]+str(ip_port)] } )
                    

                    # iost_print(IOST_SaveConfig_DebugLevel, ip_port, "%s" %(ip[:-1]) )
                    # if not ip_checked[ip[:-1]]:
                    #     ip_checked[ip[:-1]] = True
                    #     self.save_cfg.IOST_Data.update( { ip[:-1] : self.IOST_Data[ip[:-1]] } )

                    # self.save_cfg.IOST_Data.update( { ip[:-1]+str(ip_port) : self.IOST_Data[ip[:-1]+str(ip_port)] } )

            # if check button 'Save the testcases of IP which have disabed' : Disable 
            else:
                if not Str2Bool(self.IOST_Data[ip[:-1]]):
                    pass
                else: 
                    for ip_port in range(0, self.IOST_Data[ip[:-1]+'_PortNum']):
                        if Str2Bool( self.IOST_Data[ip[:-1]+str(ip_port)][0] ) : 
                            if not ip_checked[ip[:-1]]:
                                ip_checked[ip[:-1]] = True
                                self.save_cfg.IOST_Data.update( { ip[:-1] : self.IOST_Data[ip[:-1]] } )

                            self.save_cfg.IOST_Data.update( { ip[:-1]+str(ip_port) : self.IOST_Data[ip[:-1]+str(ip_port)] } )
                        else:
                            continue

        if IOST_SaveConfig_DebugEnable: 
            print "=================================================================="
            print "                        Station_info                              "
            print "=================================================================="
            pprint (self.save_cfg.IOST_Objs)
            print "==================================================================\n\n"

            print "\n\n=================================================================="
            print "                        Testcases                                  "
            print "=================================================================="
            pprint (self.save_cfg.IOST_Data)
            print "==================================================================\n\n"

        if self.SaveConfig_StationInfo_SaveEnable:
            iost_print(IOST_SaveConfig_DebugLevel, "Save Configure File to StationInfo", "")
            self.SaveConfig_WriteConfigFile(self.SaveConfig_StationInfoPath, self.save_cfg.IOST_Objs)
        if self.SaveConfig_Testcase_SaveEnable:
            iost_print(IOST_SaveConfig_DebugLevel, "Save Configure File to the Testcase", "")
            self.SaveConfig_WriteConfigFile(self.SaveConfig_TestcasesPath, self.save_cfg.IOST_Data)
            
        self.SaveConfig_Hide()
        return True

    def SaveConfig_SaveDialog(self, current_filename, title_str=""):
        ""
        if title_str=="":
            title_str = "Save Config Files"
        dlg = gtk.FileChooserDialog(title=title_str,  action=gtk.FILE_CHOOSER_ACTION_SAVE)
        dlg.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        dlg.add_button(gtk.STOCK_SAVE, gtk.RESPONSE_OK)
        dlg.set_do_overwrite_confirmation(True)
        #Set file name
        if os.path.isdir(current_filename):            
            dlg.set_current_name("")
            dlg.set_current_folder( current_filename )
        else:
            dir_path = os.path.dirname(os.path.realpath(current_filename))
            dlg.set_current_folder( dir_path )
            dlg.set_current_name(os.path.basename(current_filename))

        if dlg.run() == gtk.RESPONSE_OK:
            filename = dlg.get_filename()
            iost_print(IOST_SaveConfig_DebugLevel, filename, "SaveConfig_SaveDialog --> filename :")
            dlg.destroy()
            return filename
        else:
            dlg.destroy()
            return current_filename        

    def SaveConfig_WriteConfigFile(self, file_name='', data=None):
        ""
        try:            
            self.WriteFile(file_name, data)
        except:
            MsgBox( "%s: %s" %("Can't open file for writting", file_name) )
            return False
            
            
        

# try:                
#     # f = open(filename, "w")
#     # f.write(buff)
#     # f.close()
    
#     # WriteFile(self, file_name="", data=None):
#     # self.WriteFile(self.IOST_Data["IOST_Path"] + "/Temp_Configs/Data_Config_Before_ResetAll.json", self.IOST_Data)
#     self.WriteFile(filename)
    
# except:
#     dlg.destroy()
#     MsgBox("%s: %s" % (_("Can't open file for writting"), filename) )
#     return