# coding=cp1251
'''
Created on 16.10.2012

@author: Scondo

Замена встроенных функций ТБ 6.9
'''
from __future__ import division
import re
import string
#import uuid
from math import trunc
from os.path import exists
import bisect
re_service_c = ['.', '^', '$', '*', '+', '?', '(', ')', '{', '}', '|']

aliases = {'match': 'Match',
         'up': 'string.upper',
         'pos': 'string.find',
         'insert': 'StrIns',
         'extractword': 'ExtractWord',
         'extractwords': 'ExtractWords',
         'wordscount': 'WordsCount',
         'if': 'if_func',
         'trim': 'string.strip',
         'trimleft': 'string.lstrip',
         'trimright': 'string.rstrip',
         'substr': 'Substr',
         #'getguid': 'GetGuid',
         'trunc': 'Trunc',
         'existfile': 'exists',
         'addinarray': 'AddInArray',
         'str16': 'Str16'
         }


class TBArr:
    def __init__(self, initval=0):
        self._initval = initval
        self._impl = []

    def __getitem__(self, n):
        return self._impl[n - 1]

    def __setitem__(self, n, val):
        # add next
        if n == len(self._impl) + 1:
            self._impl.append(val)
            return
        if n > len(self._impl):
            self._impl.extend((n - len(self._impl)) * self._initval)
        self._impl[n - 1] = val

    def __len__(self):
        return len(self._impl)

    def find(self, value):
        try:
            return self._impl.index(value)
        except ValueError:
            return -1


class FAsArr:
    def __init__(self, func):
        self.func = func

    def __getitem__(self, _in):
        return self.func(_in)


def TBMask2PyRegExp(Mask):
    remask = r'\A'
    for c in Mask:
        if c == '*':
            remask = remask + '.*'
        elif c == '?':
            remask = remask + '.'
        elif c == '!':
            remask = remask + '($|[.].*)'
        elif c in re_service_c:
            remask = remask + '[' + c + ']'
        else:
            remask = remask + c
    return remask + r'\Z'


def Match(src, mask):
    remask = TBMask2PyRegExp(mask)
    return re.match(remask, src)


def StrIns(substr, text, pos):
    return text[:pos] + substr + text[pos:]


def WordsCount(n, text, sep):
    return len(text.split(sep))


def ExtractWord(n, text, sep):
    return text.split(sep)[n - 1]


def ExtractWords(n, kol, text, sep):
    return sep.join(text.split(sep)[n - 1:n - 1 + kol])


def if_func(cond, arg2=None, arg3=None):
    if cond is dict:
        pass
    else:
        return arg2 if cond else arg3


def Substr(stri, first, n):
    #          0-based: included
    return stri[first - 1:first - 1 + n]


#def GetGuid():
#    return "{" + str(uuid.uuid4()) + "}"


def Trunc(var, n=0):
    k = 10 ^ n
    var = float(var)
    return trunc(var * k) / k


def AddInArray(arr, sort, dup, *values):
    if not sort:
        if dup:
            arr._impl.extend(values)
        else:
            for value in values:
                if arr.find(value) == -1:
                    arr._impl.append(value)
    else:
        for value in values:
            if dup or arr.find(value) == -1:
                bisect.insort(arr._impl, value)


def Str16(value, width=8):
    return format(value, '0' + str(width) + 'X')
