import re
import shlex


from tklib.tkobject import tkObject



"""
    sublist = {   # 置換元文字列:置換する文字列
        's1': 'target1',
        's2': 'target2',
        's3': 'target3'
        }

repatter = re.compile(pattern)
matchOB = repatter.match(text)
    print matchOB.group() # マッチした文字列を返す # ca
    print matchOB.start() # マッチの開始位置を返す # 0
    print matchOB.end()  # マッチの終了位置を返す # 2
    print matchOB.span()  # マッチの位置(start, end)を含むタプルを返す # (0, 2)

    def SubstituteAll(self, sublist, str):
        table = str.maketrans(sublist)
        return str.translate(table)
"""


last_res = None


def GetReg_flag(flag = ''):
    re_flag = 0
    if 'i' in flag:
        re_flag |= re.IGNORECASE
    if 's' in flag:
        re_flag |= re.DOTALL
    if 'm' in flag:
        re_flag |= re.MULTILINE
    if 'a' in flag:
        re_flag |= re.ASCII
    if 'l' in flag:
        re_flag |= re.LOCALE
    if 'x' in flag:
       re_flag |= re.VERBOSE
    return re_flag


def DelQuote(str): 
    s = str.strip()
#    print("s [{}]".format(s))
    if Search('^\'', s) and Search('\'$', s):
        s = Sub('^\'', '', s)
        s = Sub('\'$', '', s)
    elif Search('^\"', s) and Search('\"$', s):
        s = Sub('^\"', '', s)
        s = Sub('\"$', '', s)
    return s


def DelSpace(str): 
    return str.strip()


def DelTopSpace(str):
    return str.lstrip()


def DelLastSpace(str):
    return str.rstrip()


def Split(reg, str):
    return re.split(reg, str)


def shSplit(reg, str):
    return shlex.split(reg, str)


def Sub(reg, target, str, n = 0):
    return re.sub(reg, target, str, n)


def SubN(reg, target, str, n = 0):
    return re.subn(reg, target, str, n)

def get_result():
    return last_res
    
def Search(reg, str, flag = ''):
    global last_res
    
    re_flag = GetReg_flag(flag)
#    reg2 = re.sub(r'([\[\]\(\)])', '\\' + '\1', reg)
#    print("s, reg=", reg, reg2)
#    exit()
    match = re.search(reg, str, re_flag)
    s = []
    if match is None:
        last_res = None
        return last_res

    i = 0
    while 1:
        try:
            str = match.group(i)
            s.append(str)
        except:
            last_res = s
            return last_res
        i += 1

    last_res = s
    return last_res

def Match(reg, str, flag = ''):
    global last_res

    re_flag = GetReg_flag(flag)
#    reg2 = re.sub(r'([\[\]\(\)])', '\\' + '\1', reg)
#    print("m, reg=", reg, reg2)
#    exit()
    match = re.match(reg, str, re_flag)
    s = []
    if match is None:
        last_res = s
        return last_res

    i = 0
    while 1:
        try:
            str = match.group(i)
            s.append(str)
        except:
            return s
        i += 1

    last_res = s
    return last_res


def FindAll(reg, str, flag = ''):
    global last_res
    
    re_flag = GetReg_flag(flag)
    match = re.findall(reg, str, re_flag)
    s = []
    if match is None:
        last_res = s
        return last_res

    i = 0
    while 1:
        try:
            str = match.group(i)
            s.append(str)
        except:
            return s
        i += 1

    last_res = s
    return last_res


def FindIter(reg, str, flag = ''):
    global last_res
    
    re_flag = GetReg_flag(flag)
    iter = re.finditer(reg, str, re_flag)
#    print("iter=", iter)
#    print("reg=", reg)
#    print("str=", str)
#    print("re_flag=", re_flag)
    s = []
    if iter is None:
        last_res = s
        return last_res
    
    for match in iter:
#        print("match=", match)
        s1 = []
        i = 0
        while 1:
            try:
                ss = match.group(i)
#                print("i=", i, "  ss=", ss)
                s1.append(ss)
            except:
                break
            i += 1
        s.append(s1)
#    print("s=", s)

    last_res = s
    return last_res

class tkRegExp(tkObject):
    """ 
    tklib Regular Expression class
    """

    def __init__(self, **args):
        self.method  = None

    def __del__(self):
        pass

    def __str__(self):
        return self.ClassPath()


    def FindIter(self, reg, str, flag = ''):
        return FindIter(reg, str, flag)


def main():
    str = '  \" abc\"  '
    l = DelQuote(str)
    print("str [{}]".format(str))
    print("DelQuote: [{}]".format(l))

    str = '  \'\" abc\"\'  '
    l = DelQuote(str)
    print("")
    print("str [{}]".format(str))
    print("DelQuote: [{}]".format(l))

    str = 'Title = abc def\n' \
          'Name = dkl\n'
    print("")
    print("str:")
    print(str)

    print("")
    print("module")
    l = FindIter(r'^\s*(\S+)\s*=\s*(.*)\s*$', str, 'im')
    print("  l(flag=im):", l)
    l = FindIter(r'^\s*(\S+)\s*=\s*(.*)\s*$', str, 'is')
    print("  l(flag=is):", l)

    print("")
    print("class")
    reg = tkRegExp()
    l = reg.FindIter(r'^\s*(\S+)\s*=\s*(.*)\s*$', str, 'im')
    print("  l(flag=im):", l)
    l = reg.FindIter(r'^\s*(\S+)\s*=\s*(.*)\s*$', str, 'isx')
    print("  l(flag=isx):", l)


if __name__ == "__main__":
    main()
