# -*- coding: windows-1251 -*-
from datetime import date


def tb_date(val):
    val = val.split('.')
    if len(val) != 3:
        return
    return date(int(val[0]), int(val[1]), int(val[2]))


def typecheck(arr):
    for it in arr:
        if it is not None:
            return type(it)


def write_array(f, varname, src):
    if typecheck(src) == date:
        def makerow(pair):
            if pair[0] is None:
                return '{}[{}]=100.1.1'.format(varname, pair[1]) + chr(10)
            return '{}[{}]={:%Y.%m.%d}'.format(varname, pair[1], pair[0]) + chr(10)
    elif typecheck(src) == unicode:
        def makerow(pair):
            return '{}[{}]={}'.format(varname, pair[1], pair[0].encode('1251')) + chr(10)
    else:
        def makerow(pair):
            return '{}[{}]={}'.format(varname, pair[1], pair[0]) + chr(10)

    if isinstance(f, basestring):
        f = open(f, 'w')
        closeme = True
    else:
        closeme = False

    f.writelines(map(makerow, zip(src, range(1, len(src) + 1))))
    if closeme:
        f.close()

def read_array(filename,varname,convert=str):
    f=open(filename)
    res={}
    if convert == 'date':
        convert = tb_date
    for row in f:
        if row.startswith(varname):
            row=row.replace(varname,'',1)
            row=row.partition("=")
            if row[0].startswith("[") and row[0].endswith("]") and row[0][1:-1].isdigit:
                res[int(row[0][1:-1])]=convert(row[2][:-1])
        #TODO: Multistrings
    f.close()
    return res

def dict_to_gen(src,default='',shiftat0=False):
    if shiftat0:
        yield default
    i=1
    while True:
        yield src.get(i,default)
        i+=1

def dict_to_list(src,default='',shiftat0=False):
    if shiftat0:
        res=[default]
    else:
        res=[]
        
    for i in xrange(1,max(src.keys())+1):
        res.append(src.get(i,default))
    return res            
    