# 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
import datetime
import copy
from os.path import exists
import bisect
re_service_c = ['.', '^', '$', '*', '+', '?', '(', ')', '{', '}', '|']

aliases = {'match': 'Match',
         'up': 'string.upper',
         'pos': 'string.find',
         u'поз': 'string.find',
         'insert': 'StrIns',
         'extractword': 'ExtractWord',
         'extractwords': 'ExtractWords',
         'wordscount': 'WordsCount',
         'if': 'if_func',
         'trim': 'string.strip',
         'trimleft': 'string.lstrip',
         'trimright': 'string.rstrip',
         'substr': 'Substr',
         u'подстр': 'Substr',
         #'getguid': 'GetGuid',
         'trunc': 'Trunc',
         u'отбр': 'Trunc',
         'existfile': 'exists',
         'addinarray': 'AddInArray',
         'str16': 'Str16',
         'dat': 'Dat',
         #'addmon': 'AddMon',
         'day': 'Day',
         u'день': 'Day',
         u'масч': 'MaSch',
         u'mon': 'Mon',
         u'мес': 'Mon',
         u'месяца': 'MonTh',
         u'year': 'Year',
         u'год': 'Year',
         'assert': 'Assert',
         'abs': 'abs'
         }


class TBDate(datetime.date):
    def __add__(self, other):
        if isinstance(other, (int, long)):
            other = datetime.timedelta(other)
        return datetime.date.__add__(self, other)

    def __sub__(self, other):
        res = datetime.date.__sub__(self, other)
        return res.days
    
    def __int__(self):
        return self.__sub__(self, datetime.date(100,1,1))

        
class TBArr(object):
    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(object):
    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')

def Day(value):
    return value.day

def Mon(value):
    return value.month

def Year(value):
    return value.year

def MonTh(value):
    value = int(value)
    if value > 12:
        value == value % 12

    if value == 0:
        return ''
    elif value == 1:
        return 'января'
    elif value == 2:
        return 'февраля'
    elif value == 3:
        return 'марта'
    elif value == 4:
        return 'апреля'
    elif value == 5:
        return 'мая'
    elif value == 6:
        return 'июня'
    elif value == 7:
        return 'июля'
    elif value == 8:
        return 'августа'
    elif value == 9:
        return 'сентября'
    elif value == 10:
        return 'октября'
    elif value == 11:
        return 'ноября'
    elif value == 12:
        return 'декабря'

def Dat(d, m, y):
    return TBDate(y, m, d)

def Assert(v1, v2=''):
    assert v1, v2

def MaSch(value):
    if len(value) == 1:
        return '0' + value
    else:
        return value