# -*- coding: utf-8 -*-
#
# $Date: 2012-08-20 17:49:07 +0900 (月, 20 8 2012) $
# $Rev: 2 $
#
from __future__ import print_function
import wx
from wx import xrc

import os

red   =(255,0  ,0  ,255)
blue  =(0  ,0  ,255,255)
green =(0  ,255,0  ,255)
white =(255,255,255,255)
black =(0  ,0  ,0  ,255)
gray  =(246,244,241,255)
yellow=(255,255,0  ,255)

class FileNotFound(Exception):
    def __init__(self, filename):
        self.filename = filename
        return

    def __str__(self):
        return repr(self.filename)

class ControlNotFound(Exception):
    def __init__(self, name):
        self.name = name
        return

    def __str__(self):
        return 'name: ' + repr(self.name)

class XrcBase(object):
    __resources = dict()

    @staticmethod
    def getResource(filename):
        fullpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
        fullpath = os.path.join(fullpath, filename)

        if not os.path.exists(fullpath):
            raise FileNotFound(fullpath)

        if filename in XrcBase.__resources:
            resource = XrcBase.__resources[filename]
            pass
        else:
            resource = xrc.EmptyXmlResource()
            resource.Load(filename)
            XrcBase.__resources[filename] = resource
            pass

        return resource

    def getControl(self, name):
        control = xrc.XRCCTRL(self, name)

        #if control == None:
        #    raise ControlNotFound(name)
        return control

    def bindControl(self,name,eventhandler,callfunc):
        ctrl=self.getControl(name)
        ctrl.Bind(eventhandler,callfunc)

    def hideControl(self,name):
        ctrl=self.getControl(name)
        if ctrl!=None:
            ctrl.Hide()
        else:
            print("====",name)

    def showControl(self,name):
        ctrl=self.getControl(name)
        if ctrl!=None:
            ctrl.Show()
        else:
            print("====",name)

    def setColor(self,name,tag,colour):
        ctrl=self.getControl(name)
        if ctrl!=None:
            if tag=="fore":
                ctrl.SetForegroundColour(colour)
            elif tag=="back":
                ctrl.SetBackgroundColour(colour)
            else:
                pass
        else:
            pass

    def getColor(self,name,tag):
        ctrl=self.getControl(name)
        if ctrl!=None:
            if tag=="fore":
                return ctrl.GetForegroundColour()
            elif tag=="back":
                return ctrl.GetBackgroundColour()
            else:
                return None
        else:
            return None

    def setValue(self,name,valstr=None,valnum=None):
        ctrl=self.getControl(name)
        if valstr!=None:
            if type(valstr)==str or type(valstr)==unicode:
                pass
            else:
                valstr="---"

        if type(ctrl)==wx._controls.StaticText:
            if valstr!=None:
                ctrl.SetLabel(valstr)
        elif type(ctrl)==wx._controls.TextCtrl:
            if valstr!=None:
                ctrl.SetValue(valstr)
        elif type(ctrl)==wx._controls.Button:
            if valstr!=None:
                ctrl.SetLabel(valstr)
            if valnum!=None:
                ctrl.SetValue(valnum)
        elif type(ctrl)==wx._controls.ToggleButton:
            if valstr!=None:
                ctrl.SetLabel(valstr)
            if valnum!=None:
                ctrl.SetValue(valnum)
        elif type(ctrl)==wx._controls.Choice:
            if valnum!=None:
                ctrl.SetSelection(valnum)
        else:
            pass

    def getValue(self,name):
        ctrl=self.getControl(name)
        if type(ctrl)==wx._controls.TextCtrl:
            val=ctrl.GetValue()
        elif type(ctrl)==wx._controls.ComboBox:
            val=str(ctrl.GetSelection())
        elif type(ctrl)==wx._controls.Choice:
            val=str(ctrl.GetSelection())
        elif type(ctrl)==wx._controls.ToggleButton:
            val=ctrl.GetValue()
        else:
            print(type(ctrl),name)
            val=0
        return val


    def setControl(self, name,flag=True):
        ctrl=self.getControl(name)
        ctrl.Enable(flag)


    def unsetControl(self, name):
        ctrl=self.getControl(name)
        ctrl.Disable()

    def setBlink(self,name,color1,color2,flag):
        ctrl=self.getControl(name)
        if ctrl!=None:
            if flag=="back":
                if ctrl.GetBackgroundColour()==color1:
                    ctrl.SetBackgroundColour(color2)
                elif ctrl.GetBackgroundColour()==color2:
                    ctrl.SetBackgroundColour(color1)
                else:
                    ctrl.SetBackgroundColour(color1)
            if flag=="fore":
                if ctrl.GetForegroundColour()==color1:
                    ctrl.SetForegroundColour(color2)
                elif ctrl.GetForegroundColour()==color2:
                    ctrl.SetForegroundColour(color1)
                else:
                    ctrl.SetForegroundColour(color1)
        else:
            print(type(ctrl))

    def setNumberControl(self, name):
        obj=self.getControl(name)

        if "SetValue" in dir(obj):
            obj.Bind(wx.EVT_TEXT,self.checkNumberControl)

    def checkNumberControl(self,event):       # テキストコントロールに数字だけ入力モードにする。
        obj=event.GetEventObject()
        if type(obj)==wx._controls.TextCtrl:
            text=obj.GetValue()
            if len(text)!=0: 
                condition  = text[-1].isdigit() # isdigit
                condition += text[-1]=="."      # とりあえず可 OR
                condition += text[-1]=="+"      #           OR
                condition += text[-1]=="-"      #           OR
                condition += text[-1]=="e"      #           OR
                condition += text[-1]=="E"      #           OR
                #AND
                condition *=text.count(".")<2   # 2個以上は不可
                condition *=text.count("e")<2
                condition *=text.count("E")<2
                #AND
                if text[-1]=="+":
                    if len(text)==1:            # 最初は可
                        condition *=True
                    else:
                        ind=text[1:].index("+")
                        if text[ind]=="e" or text[ind]=="E": # Eの次でも可
                            condition *=True
                        else:
                            condition *=False
                #AND
                if text[-1]=="-":
                    if len(text)==1:            # 最初は可
                        condition *=True
                    else:
                        ind=text[1:].index("-")
                        if text[ind]=="e" or text[ind]=="E": # Eの次でも可
                            condition *=True
                        else:
                            condition *=False
                #AND
                if text[-1]==".":
                    if len(text)==1:            # 最初は可
                        condition *=True
                    else:
                        if text[-2]=="e" or text[-2]=="E": # Eの次は不可
                            condition *=False
                        else:
                            condition *=True
                #AND
                if text[-1]=="e" or text[-1]=="e":
                    if len(text)==1:            # 最初は不可
                        condition *=False
                    else:
                        if text[-2]==".": # Eの次は不可
                            condition *=False
                        else:
                            condition *=True

                if condition > 0:
                    pass
                else:
                    if len(text)!=0:
                        obj.SetValue(text[:-1])


class FrameBase(XrcBase, wx.Frame):
    def __init__(self, filename, frameName):
        resource = XrcBase.getResource(filename)

        pre = wx.PreFrame()
        resource.LoadOnFrame(pre, None, frameName)
        self.PostCreate(pre)
        return

class DialogBase(XrcBase, wx.Dialog):
    def __init__(self, parent, filename, dialogName):
        resource = XrcBase.getResource(filename)

        pre = wx.PreDialog()
        resource.LoadOnDialog(pre, parent, dialogName)
        self.PostCreate(pre)
        self.CenterOnParent()
        return

class PanelBase(XrcBase, wx.Panel):
    def __init__(self, parent, filename, panelName):
        resource = XrcBase.getResource(filename)

        pre = wx.PrePanel()
        resource.LoadOnPanel(pre, parent, panelName)
        self.PostCreate(pre)
        return
