from __future__ import print_function
from __future__ import absolute_import
import sys
import time
import os
import math
import numpy
import inspect
import wx
import wx.lib.agw.ultimatelistctrl as ULC
from . import subUtils.xrc.base as xrcbase
from . import subUtils.execCommandCommon as ecc
import utsusemi.DNA.ana.Reduction.SearchPathDNA as SPD
#-------------------------------------------------------------------------------------------------
#AGW(http://xoomer.virgilio.it/infinity77/AGW_Docs/), ver > 0.9.1 ?
#-------------------------------------------------------------------------------------------------

NUMBER_OF_ROW        = 50

DEFAULT_DATA_PATH    = os.path.join(os.path.dirname(os.path.abspath(__file__)))

CTRL_COLUMN_WIDTHS   = [30,90,90,120,130,90,90]
CTRL_COLUMN_LABELS   = [" ",
                        "      RunNo",
                        "TOF offset",
                        "         Slit",
                        "        TrigNet",
                        " Start Time ",
                        "  End Time "]

NUM_OF_CONTROL       = len(CTRL_COLUMN_LABELS)

CTRL_TABLE_SIZE      = [sum(CTRL_COLUMN_WIDTHS)+240,400]

THERMOMETER_TYPE     = ["A","B","C1","C2","C3","C4","D1","D2","D3","D4"]

DEFAULT_SETTING_PATH = "default.csv"

#-------------------------------------------------------------------------------------------------
def _isFloatStr(val):
    try:
        ret=float(val)
        return True
    except:
        return False
#-------------------------------------------------------------------------------------------------
def _isIntStr(val):
    try:
        ret=int(val)
        return True
    except:
        return False
#-------------------------------------------------------------------------------------------------
class MainPanel(xrcbase.PanelBase):
    def __init__(self, parent,bgcolour=(0,0,255)):
        xrcbase.PanelBase.__init__(self, parent, 'dataReduction.xrc', 'mainPanel')

        self.parent = parent

        ctrlPanel = self.getControl('ctrl panel')
        self.ctrlPanelObj = CtrlPanel(ctrlPanel)
        ctrlSizer = wx.BoxSizer(wx.VERTICAL)
        ctrlSizer.Add(self.ctrlPanelObj, flag = wx.EXPAND, proportion=1)
        ctrlPanel.SetSizer(ctrlSizer)
        ctrlPanel.SetMinSize(CTRL_TABLE_SIZE)

        objnames = ["start button", "clear button", "quit button","binInfo load button",
                    "maskInfo load button", "effInfo load button", "setting load button",
                    "setting save button", "read temp button", "etRangeNormRB", "etRangeUserRB"]
        evtType  = [wx.EVT_BUTTON, wx.EVT_BUTTON, wx.EVT_BUTTON, wx.EVT_BUTTON, wx.EVT_BUTTON, wx.EVT_BUTTON,
                    wx.EVT_BUTTON, wx.EVT_BUTTON, wx.EVT_BUTTON, wx.EVT_RADIOBUTTON, wx.EVT_RADIOBUTTON]
        funcs    = [self.start, self.clear, self.close, self.popupFileDialog, self.popupFileDialog,
                    self.popupFileDialog, self.popupFileDialog, self.popupFileDialog, self.onReadTemp,
                    self.selectETobject,self.selectETobject]

        for name,evt,func in zip(objnames,evtType,funcs):
            self.getControl(name).Bind(evt,func)

        self.selectETobject(None)
        self.getControl("thermometer Type").SetItems(THERMOMETER_TYPE)
        self.getControl("thermometer Type").SetSelection(0)

        self.initialize()
#-------------------------------------------------------------------------------------------------
    def _getValueFromList(self,listVal,default,*args):
        depth = len(args)
        try:
            if depth==1:
                val=listVal[args[0]]
            elif depth==2:
                val=listVal[args[0]][args[1]]
            elif depth==3:
                val=listVal[args[0]][args[1]][args[2]]
            elif depth==4:
                val=listVal[args[0]][args[1]][args[2]][args[3]]
            else:
                val=default
        except:
            val=default

        return val
#-------------------------------------------------------------------------------------------------
    def initialize(self):
        self.loadSetting(DEFAULT_SETTING_PATH)
        pass
#-------------------------------------------------------------------------------------------------
    def selectETobject(self, event):
        flag = self.getControl("etRangeNormRB").GetValue()
        objnames = ["binInfo label", "binInfo Path", "binInfo load button"]
        for name in objnames:
            self.getControl(name).Enable(not flag)

        objnames = ["Emin label", "Emin control", "Emax label", "Emax control",
                    "Ebin label", "Ebin control", "eunit label"]
        for name in objnames:
            self.getControl(name).Enable(flag)
#-------------------------------------------------------------------------------------------------
    def popupFileDialog(self, event):

        if type(event.GetEventObject())==wx._controls.Button:
            buttonName = event.GetEventObject().GetName()
        elif type(event.GetEventObject())==wx._core.Menu:
            buttonName = event.GetEventObject().GetLabel(event.GetId())

        if buttonName == "setting save button":
            title = 'Save File Specify'
            dialogType = wx.SAVE
            fileDialog = wx.FileDialog(self, title,
                                             style = dialogType,
                                             defaultDir = DEFAULT_DATA_PATH)
            #wildcard = 'Text file (*.txt)|*.txt'
            #fileDialog = wx.FileDialog(self, title,
            #                                 style = dialogType,
            #                                 wildcard = wildcard)

        else:
            title = 'Open File Specify('+buttonName+')'
            dialogType = wx.FD_OPEN

            if buttonName=="maskInfo load button":
                #defaultDataDir = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml")
                ret = SPD.CheckForOutput( "xml" )
                if ret=="":
                    raise UserWarning( "MultiDataCobine/MainFrame::popupFileDialog >> Not found xml directory." )
                else:
                    defaultDataDir = ret
            elif buttonName=="effInfo load button":
                #defaultDataDir = os.path.join(os.environ["HOME"],"ana","setup")
                ret = SPD.CheckForOutput( "setup" )
                if ret=="":
                    raise UserWarning( "MultiDataCobine/MainFrame::popupFileDialog >> Not found setup directory." )
                else:
                    defaultDataDir = ret
            else:
                defaultDataDir = DEFAULT_DATA_PATH

            fileDialog = wx.FileDialog(self, title,
                                             style = dialogType,
                                             defaultDir = defaultDataDir)

            #wildcard = 'Text file (*.txt)|*.txt'
            #fileDialog = wx.FileDialog(self, title,
            #                                 style = dialogType,
            #                                 wildcard = wildcard,
            #                                 defaultDir = default_datapath)
        #--------------------------------------------------------------------------------

        flag = fileDialog.ShowModal();
        if  flag == wx.ID_OK:
            filepath = str(fileDialog.GetPath())
            name=fileDialog.GetFilename()

            if buttonName   == "binInfo load button":
                obj = self.getControl("binInfo Path")
                obj.SetValue(filepath)
                self.loadBinInfo(filepath)
            elif buttonName == "maskInfo load button":
                obj = self.getControl("maskInfo Path")
                obj.SetValue(filepath)
                #self.loadMaskInfo(filepath)
            elif buttonName == "effInfo load button":
                obj = self.getControl("effInfo Path")
                obj.SetValue(filepath)
                #self.loadEfficiencyInfo(filepath)
            elif buttonName == "setting load button":
                self.loadSetting(filepath)
            elif buttonName == "setting save button":
                self.saveSetting(filepath)
            else:
                pass
            time.sleep(0.5)
            pass

        elif flag == wx.ID_CANCEL:
            if buttonName == "maskInfo load button":
                obj = self.getControl("maskInfo Path")
                obj.SetValue("")
            elif buttonName == "effInfo load button":
                obj = self.getControl("effInfo Path")
                obj.SetValue("")

#-------------------------------------------------------------------------------------------------
    def loadBinInfo(self,filepath):
        from . import subUtils.BinInfoReaderBase as BIR
        binsText = BIR._readBinInfo(filepath,"\n",",")
        return binsText
#-------------------------------------------------------------------------------------------------
    def loadMaskInfo(self,filepath):
        pass
#-------------------------------------------------------------------------------------------------
    def loadEfficiencyInfo(self,filepath):
        pass
#-------------------------------------------------------------------------------------------------
    def loadSetting(self,filepath):
        import csv
        self.clear(event=None)

        reader = csv.reader(open(filepath, 'rb'))
        lines = [line for line in reader]

        val = self._getValueFromList(lines,"0",0,0)
        if val=="1":
            self.getControl("etRangeNormRB").SetValue(1)
            self.getControl("etRangeUserRB").SetValue(0)
        else:
            self.getControl("etRangeNormRB").SetValue(0)
            self.getControl("etRangeUserRB").SetValue(1)

        val = self._getValueFromList(lines,"",0,1)
        self.getControl("Emin control").SetValue(val)

        val = self._getValueFromList(lines,"",0,2)
        self.getControl("Emax control").SetValue(val)

        val = self._getValueFromList(lines,"",0,3)
        self.getControl("Ebin control").SetValue(val)

        val = self._getValueFromList(lines,"",1,1)
        self.getControl("binInfo Path").SetValue(val)

        val = self._getValueFromList(lines,"",2,0)
        self.getControl("LambdaCenter control").SetValue(val)

        val = self._getValueFromList(lines,"",2,1)
        self.getControl("deltaLambda control").SetValue(val)

        val = self._getValueFromList(lines,"",3,0)
        self.getControl("Qmin control").SetValue(val)

        val = self._getValueFromList(lines,"",3,1)
        self.getControl("Qmax control").SetValue(val)

        val = self._getValueFromList(lines,"",3,2)
        self.getControl("Qbin control").SetValue(val)

        val = self._getValueFromList(lines,THERMOMETER_TYPE[0],4,0)
        self.getControl("thermometer Type").SetStringSelection(val)

        val = self._getValueFromList(lines,"",5,0)
        self.getControl("f chopper control").SetValue(val)

        val = self._getValueFromList(lines,"",5,1)
        self.getControl("tof source min").SetValue(val)

        val = self._getValueFromList(lines,"",5,2)
        self.getControl("tof source max").SetValue(val)

        val = self._getValueFromList(lines,"",6,0)
        self.getControl("maskInfo Path").SetValue(val)

        val = self._getValueFromList(lines,"",7,0)
        self.getControl("effInfo Path").SetValue(val)

        self.selectETobject(None)

        table_param = lines[9:]
        params = []
        ind=0
        i  =0
        for param in table_param:
            params += param[1:]
            if len(param)>0:
                if param[0]=="1":
                    ind=i
                i+=1
        self.ctrlPanelObj.setValue(params)
        self.ctrlPanelObj.setCheckRunNumber(ind)
#-------------------------------------------------------------------------------------------------
    def saveSetting(self,filepath):
        import csv
        writer = csv.writer(open(filepath, 'wb'))
        # Line 1
        data=[]
        data.append(str(int(self.getControl("etRangeNormRB").GetValue())))
        data.append(str(self.getControl("Emin control").GetValue()))
        data.append(str(self.getControl("Emax control").GetValue()))
        data.append(str(self.getControl("Ebin control").GetValue()))
        writer.writerow(data)
        # Line 2
        data=[]
        data.append(str(int(self.getControl("etRangeUserRB").GetValue())))
        data.append(str(self.getControl("binInfo Path").GetValue()))
        writer.writerow(data)
        # Line 3
        data=[]
        data.append(str(self.getControl("LambdaCenter control").GetValue()))
        data.append(str(self.getControl("deltaLambda control").GetValue()))
        writer.writerow(data)
        # Line 4
        data=[]
        data.append(str(self.getControl("Qmin control").GetValue()))
        data.append(str(self.getControl("Qmax control").GetValue()))
        data.append(str(self.getControl("Qbin control").GetValue()))
        writer.writerow(data)
        # Line 5
        data=[self.getControl("thermometer Type").GetStringSelection()]
        writer.writerow(data)
        # Line 6
        data=[]
        data.append(str(self.getControl("f chopper control").GetValue()))
        data.append(str(self.getControl("tof source min").GetValue()))
        data.append(str(self.getControl("tof source max").GetValue()))
        writer.writerow(data)
        # Line 7
        data=[self.getControl("maskInfo Path").GetValue()]
        writer.writerow(data)
        # Line 8
        data=[self.getControl("effInfo Path").GetValue()]
        writer.writerow(data)
        # Line 9
        writer.writerow([])
        # Line 10
        objs = self.ctrlPanelObj.getValue()

        for i in range(len(objs)):
            if isinstance(objs[i],bool):
                objs[i]=str(int(objs[i]))

        objs = [objs[i:i+(NUM_OF_CONTROL-1)] for i in range(0,len(objs),(NUM_OF_CONTROL-1))]

        runNo = str(self.ctrlPanelObj.getCheckRunNumber())
        for i in range(len(objs)):
            if objs[i][0]==runNo:
                objs[i] = ["1"] + objs[i]
            else:
                objs[i] = ["0"] + objs[i]

        for obj in objs:
            if "" in obj:
                pass
            else:
                writer.writerow(obj)
#-------------------------------------------------------------------------------------------------
    def onReadTemp(self,event):
        print("L :",inspect.currentframe().f_lineno,"/",__file__,"/",\
              inspect.currentframe().f_code.co_name)

        def command(runNo,thermoType):
            try:
                import uGao.MPlot as mp
                import Cmm
                EC = Cmm.CheckSampleTempByRunNumber(runNo,thermoType)
                mp.MPlot(EC)
            except:
                print("import Error / Manyo, MPlot, Cmm")

        runNo      = int(self.ctrlPanelObj.getCheckRunNumber())
        obj        = self.getControl("thermometer Type")
        thermoType = obj.GetStringSelection()

        print("# Run No.", runNo)
        print("# Thermo Type.", thermoType)

        ecc.ExecCommandCommon(command,event,args=(runNo,thermoType),objs=[obj])
#-------------------------------------------------------------------------------------------------
    def checkValues(self,vals,names):
        ret=[]
        for val,name in zip(vals,names):
            flag = not _isFloatStr(val)
            if flag:
                ret.append([val,name])

        if len(ret)==0:
            return True
        else:
            errorMessage=""
            for err in ret:
                if err[0].strip()=="":
                    errorMessage += err[1]+" is empty.\n"
                else:
                    errorMessage += err[1]+" : "+err[0]+" : is invalid.\n"

            dlg = wx.MessageDialog( self, errorMessage,  "Error",  wx.OK)
            dlg.ShowModal()

            return False
#-------------------------------------------------------------------------------------------------
    def checkFilePaths(self,vals,names):
        ret=[]
        for val,name in zip(vals,names):
            flag = not os.path.exists(val) and val.strip()!=""
            if flag:
                ret.append([val,name])

        if len(ret)==0:
            return True
        else:
            errorMessage=""
            for err in ret:
                errorMessage += err[1]+" : "+err[0]+" : is not found.\n"

            dlg = wx.MessageDialog( self, errorMessage,  "Error",  wx.OK)
            dlg.ShowModal()

            return False
#-------------------------------------------------------------------------------------------------
    def start(self,event):

        # Line 1
        etFlag = self.getControl("etRangeNormRB").GetValue()
        eMin = self.getControl("Emin control").GetValue()
        eMax = self.getControl("Emax control").GetValue()
        eBin = self.getControl("Ebin control").GetValue()

        # Line 2
        binInfoPath = self.getControl("binInfo Path").GetValue()

        # Line 3
        LambdaCenter = self.getControl("LambdaCenter control").GetValue()
        deltaLambda  = self.getControl("deltaLambda control").GetValue()

        # Line 4
        qMin = self.getControl("Qmin control").GetValue()
        qMax = self.getControl("Qmax control").GetValue()
        qBin = self.getControl("Qbin control").GetValue()

        # Line 6
        fChop = self.getControl("f chopper control").GetValue()
        tofSrcMin = self.getControl("tof source min").GetValue()
        tofSrcMax = self.getControl("tof source max").GetValue()

        # Line 7
        maskInfoPath = self.getControl("maskInfo Path").GetValue()
        # Line 8
        effInfoPath  = self.getControl("effInfo Path").GetValue()

        # Line 10
        objs = self.ctrlPanelObj.getValue()
        for i in range(len(objs)):
            if isinstance(objs[i],bool):
                objs[i]=str(int(objs[i]))

        objs = [objs[i:i+(NUM_OF_CONTROL-1)] for i in range(0,len(objs),(NUM_OF_CONTROL-1))]
        i=0
        j=0
        index=[]
        while i<len(objs):
            if "" in objs[i] or u'' in objs[i]:
                del objs[i]
            else:
                index.append(j)
                i+=1
            j+=1

        slitwidths  = [int(val[2]) for val in objs] # if val==1:3cm, else if val==0:1cm.
        useTrignets = [int(val[3]) for val in objs] # if val==1:Use, else if val==0:NotUse.

        timeRanges  = [val[4]+","+val[5] for val in objs]

        if etFlag:
            hwParam     = eBin + "," + eMin + "," + eMax
        else:
            hwParam     = self.loadBinInfo(binInfoPath)

        lambdaParam = LambdaCenter + "," + deltaLambda

        tofSource   = tofSrcMin + "," + tofSrcMax

        # Error Check
        vals  = [eMin,eMax,eBin,LambdaCenter,deltaLambda,qMin,qMax,qBin,fChop,tofSrcMin,tofSrcMax]
        names = ["emin","emax","ebin","LambdaCenter","deltaLambda","qmin","qmax","qbin","f chopper",
                 "tof source start","tof source end"]
        for j,obj in zip(index,objs):
            runNo     = obj[0]
            tofOffset = obj[1]
            startTime = obj[4]
            endTime   = obj[5]
            js = str(j+1)
            vals  += [runNo,tofOffset,startTime,endTime]
            names += ["runNo"+js,"tofOffset"+js,"startTime"+js,"endTime"+js]
        ret1 = self.checkValues(vals,names)

        if etFlag:
            vals  = [maskInfoPath,effInfoPath]
            names = ["mask info path","efficiency info path"]
        else:
            vals  = [binInfoPath,maskInfoPath,effInfoPath]
            names = ["bin info path","mask info path","efficiency info path"]
        ret2 = self.checkFilePaths(vals,names)

        if not (ret1 and ret2):
            pass
        else:
            startQ = float(qMin)
            endQ   = float(qMax)
            deltaQ = float(qBin)
            fChop  = float(fChop)
            runNos = [int(val[0])   for val in objs]
            offsets= [float(val[1]) for val in objs]
            from . import command
            ecc.ExecCommandCommon(command.command,event,
                                  args=(runNos, offsets, timeRanges, hwParam, lambdaParam,
                                        tofSource, startQ, endQ, deltaQ, slitwidths, useTrignets,fChop,
                                        maskInfoPath, effInfoPath),
                                  objs=[self])
            pass
#-------------------------------------------------------------------------------------------------
    def clear(self,event):

        self.getControl("etRangeNormRB").SetValue(1)
        self.getControl("etRangeUserRB").SetValue(0)

        objnames =["Emin control", "Emax control", "Ebin control", "binInfo Path",
                   "LambdaCenter control", "deltaLambda control", "Qmin control",
                   "Qmax control", "Qbin control", "f chopper control", "tof source min",
                   "tof source max", "maskInfo Path", "effInfo Path"]
        for name in objnames:
            self.getControl(name).SetValue("")

        self.getControl("thermometer Type").SetStringSelection(THERMOMETER_TYPE[0])

        self.ctrlPanelObj.clear()
#-------------------------------------------------------------------------------------------------
    def close(self,event):
        self.parent.Destroy()
        pass
#-------------------------------------------------------------------------------------------------
class CtrlPanel(wx.Panel):
    def __init__(self,parent):
        wx.Panel.__init__(self, parent)

        scroll = wx.ScrolledWindow(self, -1)
        scroll.SetScrollRate(1,1)

        self.ctrlObjs=[]

        self.checkBoxObjs=[]

        ulist = ULC.UltimateListCtrl(scroll, wx.ID_ANY,
                                     agwStyle=wx.LC_REPORT|\
                                              wx.LC_VRULES|\
                                              wx.LC_HRULES|\
                                              wx.LC_SINGLE_SEL|\
                                              ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)

        for i,label in enumerate(CTRL_COLUMN_LABELS):
            ulist.InsertColumn(i, label)

        for i,width in enumerate(CTRL_COLUMN_WIDTHS):
            ulist.SetColumnWidth(i,width)

        for i in range(NUMBER_OF_ROW):
            index = ulist.InsertStringItem(sys.maxsize, "")
            checkbox_1 = wx.CheckBox(ulist,wx.ID_ANY,"")
            ulist.SetItemWindow(index, 0, checkbox_1)
            self.checkBoxObjs.append(checkbox_1)
            checkbox_1.Bind(wx.EVT_CHECKBOX,self.onCheckRunNumber)

            text_1 = wx.TextCtrl(ulist, wx.ID_ANY, style = wx.TE_RIGHT)
            ulist.SetItemWindow(index, 1, text_1)
            self.ctrlObjs.append(text_1)

            text_2 = wx.TextCtrl(ulist, wx.ID_ANY, style = wx.TE_RIGHT)
            ulist.SetItemWindow(index, 2, text_2)
            self.ctrlObjs.append(text_2)

            radio_panel1,btn_obj1 = self.getRadioBoxPanel(ulist,wx.ID_ANY,"3cm","1cm")
            ulist.SetItemWindow(index, 3, radio_panel1)
            self.ctrlObjs.append(btn_obj1)

            radio_panel2,btn_obj2 = self.getRadioBoxPanel(ulist,wx.ID_ANY,"Use","NotUse")
            ulist.SetItemWindow(index, 4, radio_panel2)
            self.ctrlObjs.append(btn_obj2)

            text_3 = wx.TextCtrl(ulist, wx.ID_ANY, style = wx.TE_RIGHT)
            ulist.SetItemWindow(index, 5, text_3)
            self.ctrlObjs.append(text_3)

            text_4 = wx.TextCtrl(ulist, wx.ID_ANY, style = wx.TE_RIGHT)
            ulist.SetItemWindow(index, 6, text_4)
            self.ctrlObjs.append(text_4)

        self.checkBoxObjs[0].SetValue(True)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ulist, 1, wx.EXPAND)
        scroll.SetSizer(sizer)

        sizerf = wx.BoxSizer(wx.VERTICAL)
        sizerf.Add(scroll, 1, wx.EXPAND)
        self.SetSizer(sizerf)
#-------------------------------------------------------------------------------------------------
    def onCheckRunNumber(self,event):
        obj=event.GetEventObject()
        if obj.GetValue():
            for cb in self.checkBoxObjs:
                cb.SetValue(False)
        else:
            pass
        obj.SetValue(True)
#-------------------------------------------------------------------------------------------------
    def getCheckRunNumber(self):
        for i,cb in enumerate(self.checkBoxObjs):
            if cb.GetValue():
                return self.ctrlObjs[i*(NUM_OF_CONTROL-1)].GetValue()
#-------------------------------------------------------------------------------------------------
    def setCheckRunNumber(self,val):
        for i,cb in enumerate(self.checkBoxObjs):
            if i==val:
                cb.SetValue(1)
            else:
                cb.SetValue(0)
#-------------------------------------------------------------------------------------------------
    def getValue(self):
        ret=[obj.GetValue() for obj in self.ctrlObjs]
        return ret
#-------------------------------------------------------------------------------------------------
    def setValue(self,vals):
        for i,val in enumerate(vals):
            if i<len(self.ctrlObjs):
                if isinstance(self.ctrlObjs[i], wx._controls.TextCtrl):
                    self.ctrlObjs[i].SetValue(val)
                elif isinstance(self.ctrlObjs[i], wx._controls.RadioButton):
                    val = int(val)
                    objs = [ item.GetWindow() for item in self.ctrlObjs[i].GetParent().GetSizer().GetChildren() ]
                    if val==1:
                        objs[0].SetValue(True)
                    else:
                        objs[1].SetValue(True)
                    #self.ctrlObjs[i].SetValue(val)
                else:
                    pass
#-------------------------------------------------------------------------------------------------
    def clear(self):
        for i,cb in enumerate(self.checkBoxObjs):
            if i==0:
                cb.SetValue(True)
            else:
                cb.SetValue(False)

        for i,obj in enumerate(self.ctrlObjs):
            if i%(NUM_OF_CONTROL-1)==2 or i%(NUM_OF_CONTROL-1)==3:
                obj.SetValue(True)
            else:
                obj.SetValue("")
#-------------------------------------------------------------------------------------------------
    def getRadioBoxPanel(self,parent,ids,choice1,choice2):
        radio_panel = wx.Panel(parent,ids)
        radio_panel.SetBackgroundColour("#FFFFFF")
        radio_sizer = wx.BoxSizer(wx.HORIZONTAL)
        radiobutton_1 = wx.RadioButton(radio_panel,wx.ID_ANY,choice1)
        radiobutton_2 = wx.RadioButton(radio_panel,wx.ID_ANY,choice2)
        radio_sizer.Add(radiobutton_1)
        radio_sizer.Add(radiobutton_2)
        radio_panel.SetSizer(radio_sizer)
        radio_panel.Fit()
        return radio_panel,radiobutton_1
#-------------------------------------------------------------------------------------------------
class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, 'Data Reduction DNA', 
                          style = wx.DEFAULT_FRAME_STYLE)

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)

        self.panel = MainPanel(self)
        sizer.Add(self.panel, flag = wx.ALL | wx.EXPAND, border = 5, proportion = 1)

        menuBar = MainMenuBar()
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self.onAbout, menuBar.menuItemAbout)
        self.Bind(wx.EVT_MENU, self.onExit , menuBar.menuItemExit )

        self.CreateStatusBar()
        self.Fit()
#-------------------------------------------------------------------------------------------------
    def onAbout(self, event):
        description = ""
        licence = "LICENCE"
        info = wx.AboutDialogInfo()
        info.SetName('Data Reduction DNA')
        info.SetVersion('0.0.0')
        info.SetDescription(description)
        info.SetCopyright('2014/xx/xx')
        info.SetWebSite('http://www/')
        #info.SetLicence(licence)
        info.AddDeveloper('')
        #info.AddDocWriter('')
        #info.AddArtist('')
        #info.AddTranslator('')
        wx.AboutBox(info)
#-------------------------------------------------------------------------------------------------
    def onExit(self, event):
        self.Destroy()
#-------------------------------------------------------------------------------------------------
class MainMenuBar(wx.MenuBar):
    def __init__(self):
        wx.MenuBar.__init__(self)

        menuFile = wx.Menu()
        self.menuItemExit               = menuFile.Append(1,'   Exit')

        menuHelp = wx.Menu()
        self.menuItemAbout              = menuHelp.Append(2,'   About')

        self.Append(menuFile,'&File')
        self.Append(menuHelp,'&Help')
#-------------------------------------------------------------------------------------------------
app = wx.PySimpleApp()

frame = MainFrame()
app.SetTopWindow(frame)
frame.Show()

app.MainLoop()
