import  wx, sys, os, gettext, string, time
import  wx.wizard as wiz
from config import generate_ip_list, drbl_ocs, all_clonezilla_save_opt, clonezilla_disk_part, server_client_input, client_action_after_save, compress_mode

cat = gettext.GNUTranslations(open('../langs/%s.mo' % os.getenv('LANG')))
_ = cat.gettext

global selected_clients, selected_disk_parts_save_opt, selected_clonezilla_save_opt, selected_server_client_opt
globla selected_img_dev_name, selected_client_action, selected_compress_mode
selected_clients = ['-nl','']
selected_disk_parts_save_opt = ['','save']
selected_clonezilla_save_opt = []
selected_server_client_opt = [''] # not count
selected_img_dev_name = ['','']
selected_client_action = ['']
selected_compress_mode = ['']

#----------------------------------------------------------------------
def makePageTitle(wizPg, title):
    sizer = wx.BoxSizer(wx.VERTICAL)
    wizPg.SetSizer(sizer)
    title = wx.StaticText(wizPg, -1, title)
    title.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD))
    sizer.Add(title, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
    sizer.Add(wx.StaticLine(wizPg, -1), 0, wx.EXPAND|wx.ALL, 5)
    return sizer

#----------------------------------------------------------------------
class checklistCtrl(wx.ListCtrl, CheckListCtrlMixin):
    def __init__(self, parent, log):
        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
        CheckListCtrlMixin.__init__(self)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)

    def OnItemActivated(self, evt):
        self.ToggleItem(evt.m_itemIndex)

    def OnCheckItem(self, index, flag):
        data = self.GetItemData(index)
        arg = all_clonezilla_save_opt[data][0]
        if flag:
	    selected_clonezilla_save_opt.append(arg)
        else:
	    selected_clonezilla_save_opt.remove(arg)

#-----------------------------------------------------------------------
class setAllClientsPage(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_next = 0

        wx.StaticText(self, -1, _('msg_select_all_clients_or_select_part_them'), pos=(10,60), size=(500,100), style=wx.TE_MULTILINE)
        wx.StaticText(self, -1, _('msg_set_all_clients_des'), pos=(10,80), size=(500,100), style=wx.TE_MULTILINE)
        ox = ['Yes', 'No']
        self.rb = wx.RadioBox(self, -1, _('msg_set_all_clients'), (10,150), (250,75), ox, 1, wx.RA_SPECIFY_COLS|wx.NO_BORDER)
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, self.rb)

    def EvtRadioBox(self, event):
        if event.GetSelection() == 0:
            selected_clients[0] = '-nl'
        if event.GetSelection() == 1:
            selected_clients[0] = '-h'

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        next = self.next
        self.fuse_next = self.fuse_next + 1
        if self.fuse_next == 2:
            if self.rb.GetSelection() == 0:
                next = next.GetNext()
        return next

    def GetPrev(self):
        self.fuse_next = 0
        prev = self.prev
        return prev

#-----------------------------------------------------------------------
class selectClientsPage(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)

        self.SelectedClientsArray = []
        self.SelectedClientsStr = ''
        self.fuse_next = self.fuse_prev = 0

        AllClientsArray = os.popen(generate_ip_list).read().split('\n')
        AllClientsArray.remove('')
        self.lb = wx.CheckListBox(self, -1, (10,50), (470,250), AllClientsArray)
        self.Bind(wx.EVT_CHECKLISTBOX, self.EvtCheckListBox, self.lb)
        self.lb.SetSelection(0)

    def EvtCheckListBox(self, event):
        index = event.GetSelection()
        label = self.lb.GetString(index)
        if self.lb.IsChecked(index):
            self.SelectedClientsArray.append(label)
        if not (self.lb.IsChecked(index)):
            self.SelectedClientsArray.remove(label)
        self.lb.SetSelection(index)     #so that (un)checking also selects (moves the highlight)

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        next = self.next
        self.fuse_prev = 0
        self.fuse_next = self.fuse_next + 1
        if self.fuse_next == 2:
            if selected_clients[0] == '-h':
		if len(self.SelectedClientsArray)==0):
                    war = wx.MessageDialog(self, 'YOU MUST CHOOSE ONE!!', 'WARNNING!!', wx.OK|wx.ICON_INFORMATION)
                    war.ShowModal()
                    war.Destroy()
                    return self
                else:
                    for x in self.SelectedClientsArray:
                        self.SelectedClientsStr = x + ' ' + self.SelectedClientsStr
                    self.SelectedClientsStr = '\"' + self.SelectedClientsStr + '\"'
                    selected_clients[1] = self.SelectedClientsStr
        return next

    def GetPrev(self):
        prev = self.prev
        self.fuse_next = 0
        return prev

#-----------------------------------------------------------------------
class clonezillaSavePage1(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_prev = 0

        list = []
        for i in range(0, len(clonezilla_disk_part)):
            list.append(clonezilla_disk_part[i][0] + '   ' + clonezilla_disk_part[i][1])

        rb = wx.RadioBox(self, -1, _('msg_choose_mode'), (35, 50), (260,90), ModeList, 1, wx.RA_SPECIFY_COLS)
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)

    def EvtRadioBox(self, event):
	selected_disk_parts_save_opt[0] = clonezilla_disk_part[event.GetSelection()][0]

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        self.fuse_prev = 0
        return self.next

    def GetPrev(self):
        self.fuse_prev = self.fuse_prev + 1
        if self.fuse_prev == 1:
            prev = self.prev
            if selected_clients[0] == '-nl':
                prev = prev.GetPrev()
        return prev

#-----------------------------------------------------------------------
class clonezillaSavePage2(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_next = 0

	list = []
	for i in range(0, len(server_client)):
	    list.append(server_client[i][0])

        rb = wx.RadioBox(self, -1, _('msg_choose_mode'), (35, 50), (260,90), list, 1, wx.RA_SPECIFY_COLS)
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)

    def EvtRadioBox(self, event):
        selected_server_client_opt[0] = server_client[event.GetSelection()][0]

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
	next = self.next
	self.fuse_next = self.fuse_next + 1
	if self.fuse_next == 2:
	    if selected_server_client_opt[0] == server_client[1][0]:
		next = next.GetNext()
        return next

    def GetPrev(self):
	self.fuse_next = 0 
        return self.prev

#----------------------------------------------------------------------
class clonezillaSavePage3(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_next = self.fuse_prev = 0

        wx.StaticText(self, -1,  _('msg_input_image_name'), (10, 160))
        self.text_img = wx.TextCtrl(self, -1, '', (10, 180), size=(200, -1))
        wx.StaticText(self, -1,  _('msg_input_device_name'), (10, 210))
        self.text_dev = wx.TextCtrl(self, -1, '', (10, 230), size=(190, -1))

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        self.fuse_prev = 0
        if self.fuse_next == 2:
            if selected_server_client_opt[0] == server_client[1][0]:
                selected_img_dev_name[0] = selected_img_dev_name[1] = ''
                #print ('selected_img_dev_name[0] is %s, selected_img_dev_name[1] is %s' % (selected_img_dev_name[0], selected_img_dev_name[1]))
            elif self.text_img.GetValue() == '' or self.text_dev.GetValue() == '':
                warnning = wx.MessageDialog(self, 'YOU MUST ENTER SOMETHING!!', 'WARNNING', wx.OK|wx.ICON_INFORMATION)
                warnning.ShowModal()
                warnning.Destroy()
                return self
            else:
                selected_img_dev_name[0] = self.text_img.GetValue()
                selected_img_dev_name[1] = self.text_dev.GetValue()
		print ('selected_img_dev_name[0] is %s, selected_img_dev_name[1] is %s' % (selected_img_dev_name[0], selected_img_dev_name[1]))
        return self.next

    def GetPrev(self):
        self.fuse_next = 0
        return self.prev

#----------------------------------------------------------------------
class clonezillaSavePage4(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_next = self.fuse_prev = 0

        ox = [_('msg_yes'), _('msg_no')]
        wx.StaticText(self, -1, _('msg_skip_set_advanced_extra_param'), (10,60), (470,100), wx.TE_MULTILINE)
        rb = wx.RadioBox(self, -1, _('msg_choose_action'), (10,100), (100,50), ox, 1, wx.RA_SPECIFY_COLS|wx.NO_BORDER)
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)
        rb.SetSelection(1)
        self.SkipExtraParam = 'no'

    def EvtRadioBox(self, event):
        if event.GetSelection() == 0:
           self.SkipExtraParam = 'yes'
        else:
           self.SkipExtraParam = 'no'

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        next = self.next
        command = command_log = ''
        self.fuse_prev = 0
        self.fuse_next = self.fuse_next + 1
        if self.fuse_next == 2:
            if self.SkipExtraParam == 'yes':
                if  selected_server_client_opt[0] == server_client[1][0]:
                    command = ('%s %s %s' % (drbl_ocs, selected_clients[0], selected_clients[1]))
                else:
                    command = ('%s %s %s %s %s' % (drbl_ocs, selected_clients[0], selected_clients[1], selected_img_dev_name[0], selected_img_dev_name[1]))
                file = open('tmp.log','w')
                os.system('sudo %s > tmp.log' % command)
                time.sleep(6)
                file.close()
                file = open('tmp.log')
                while True:
                    line = file.readline()
                    if len(line) == 0: # Zero length indicates EOF
                        break
                    command_log = command_log + line
                file.close()
                os.remove('tmp.log')
                FinalCommand.SetLabel('%s' % command)
                CommandLog.WriteText('%s' % command_log)
                for i in range(0,3):
                    next = next.GetNext()
        return next

    def GetPrev(self):
        self.fuse_next = 0
        self.fuse_prev = self.fuse_prev + 1
        prev = self.prev
        if self.fuse_prev == 1:
            if selected_img_dev_name[0] == '' and selected_img_dev_name[1] == '':
                prev = prev.GetPrev()
        return prev

#----------------------------------------------------------------------
class clonezillaSavePage5(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_next = self.fuse_prev = 0

        self.list = checkListCtrl(self, title)
        sizer = wx.BoxSizer()
        sizer.Add(self.list, 1, wx.EXPAND)
        self.SetSizer(sizer)

        self.list.InsertColumn(0, _('argument'))        #not translated
        self.list.InsertColumn(1, _('meannings'), wx.LIST_FORMAT_LEFT)  #not translated

        for key, data in selected_clonezilla_save_opt.iteritems():
            index = self.list.InsertStringItem(sys.maxint, data[0])
            self.list.SetStringItem(index, 1, data[1])
            self.list.SetItemData(index, key)

        self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE)

        self.list.CheckItem(0)
        self.list.CheckItem(1)

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        self.fuse_prev = 0
        return self.next

    def GetPrev(self):
        return self.prev

#----------------------------------------------------------------------
class clonezillaSavePage6(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)

	list = []
	for i in range(0, len(client_action_after_save)):
	    list.append(client_action_after_save[i][0] + '   ' + client_action_after_save[i][1])
        rb = wx.RadioBox(self, -1, _('msg_choose_post_mode_after_clone'), (10,100), (250,100), list, 1, wx.RA_SPECIFY_COLS|wx.NO_BORDER)
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)
        rb.SetSelection(0)
        selected_client_action[0] = '-p choose'

    def EvtRadioBox(self, event):
        selected_client_action[0] = client_action_after_save[event.GetSelection()][0]

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        return self.next

    def GetPrev(self):
        return self.prev

#----------------------------------------------------------------------
class clonezillaSavePage7(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = makePageTitle(self, title)
        self.fuse_next = 0

	list = []
	for i in range(0, len(compress_mode)):
	    list.append(compress_mode[i][0] + '   ' + compress_mode[i][1])
        rb = wx.RadioBox(self, -1, _('msg_choose_post_mode_after_clone'), (10,100), (300,100), list, 1, wx.RA_SPECIFY_COLS|wx.NO_BORDER)
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)
        rb.SetSelection(3)
        selected_compress_mode = '-z3'

    def EvtRadioBox(self, event):
        selected_compress_mode[0] =  compress_mode[event.GetSelection()][0]

    def SetNext(self, next):
        self.next = next

    def SetPrev(self, prev):
        self.prev = prev

    def GetNext(self):
        command = command_log = ''
        self.fuse_next = self.fuse_next + 1
        if self.fuse_next == 2:
            if selected_clients[0] == '-nl':
                selected_clients[0] = ''
		command = drbl_ocs + selected_clonezilla_save_opt + selected_client_action[0] + selected_compress_mode[0] + selected_clients[0] + selected_clients[1] + selected_disk_parts_save_opt
                #if FinalArgs[i] != '':
                    #command = command + FinalArgs[i] + ' '
            file = open('tmp.log','w')
            os.system('%s > tmp.log' % command)
            time.sleep(6)
            file.close()
            file = open('tmp.log')
            while True:
                line = file.readline()
                if len(line) == 0: # Zero length indicates EOF
                    break
                command_log = command_log + line
            file.close()
            os.remove('tmp.log')
            FinalCommand.SetLabel('%s' % command)
            CommandLog.WriteText('%s' % command_log)
        return self.next

    def GetPrev(self):
        self.fuse_next = 0
        return self.prev

