# -*-coding:utf-8 -*-
import os,sys
import chardet

reload(sys)
sys.setdefaultencoding('utf8')
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
'''上传文件保存处理'''
def handle_uploaded_file(f):
    BASE_DIR='F:\django_test'
    try:
        path = os.path.join(BASE_DIR, 'media\\')
        if not os.path.exists(path):
            os.makedirs(path)
        else:
            file_name = os.path.join(path, f.name.decode('utf-8'))
            size = file_convert(len(f.read()))
            destination = open(file_name, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
    except Exception, e:
        print e
    return f.name, path , size

'''文件大小换算'''
def file_convert(size,a_kilobyte_is_1024_bytes=False):
    SUFFIXES = {1000:['Bit','Kb','Mb','Gb','Tb'],1024:['Bit','Kib','Mib','Gib','Tib']}
    # multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
    multiple = 1024
    if size < 0 :
        raise valueError(u'文件大小必须是非负的！')
    if size > 0 and size < multiple:
        suffix = SUFFIXES[multiple][0]
        size = (format(float(size) / float(1), '.0f'))
        return size + suffix
    if size > multiple and size < pow(multiple, 2):
        suffix = SUFFIXES[multiple][1]
        size = (format(float(size) / float(multiple), '.2f'))
        return size + suffix
        # print '{0:.1f} {1}'.format(size,suffix)
    if size > pow(multiple, 2) and size < (pow(multiple, 3)):
        suffix = SUFFIXES[multiple][2]
        size = (format(float(size) / float(pow(multiple, 2)), '.2f'))
        return size + suffix
    else:
        raise valueError(u'文件太大，无法显示')

'''识别字符串是否是数字'''
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False
    
'''文件删除'''
# def file_del(path,filetitle):
#     del_file = os.path.join(path,filetitle)
#     if os.path.isdir(path):
#         if os.path.isfile(del_file):
#             os.remove(del_file)
#

'''按行或者整体读取文件'''
def read_txt(path,filename,total=False):
    fn = os.path.join(path,filename)
    if not total:
        f = open(fn,"r")
        lines = f.read()
        type = chardet.detect(lines)
        info = lines.decode(type["encoding"])
        print info
        return info
        f.close()
    else:
        f = open(fn, 'r+')
        line = f.readline()
        while line:
            a = line.decode('gbk')
            print a
            return a
            line = f.readline()
        f.close()
    
    
        
            
            
            
        
    
    
        
        
        
        
        
        
    
    

class FileUtil(object):
    '''文件、路径常用操作方法
	'''
    
    @staticmethod
    def read_file_data(filepath):
        '''根据路径按行读取文件, 参数filepath：文件的绝对路径
		@param filepath: 读取文件的路径
		@return: 按\t分割后的每行的数据列表
		调度程序中:
		用for fields in read_file_data(fpath)的方式读取每一行
		'''
        fin = open(filepath, 'r')
        for line in fin:
            try:
                line = line[:-1]
                if not line: continue
            except:
                continue
            try:
                fields = line.split("\t")
            except:
                continue
            # 抛出当前行的分割列表
            yield fields
        fin.close()
    
    @staticmethod
    def transform_list_to_dict(para_list):
        """把['a', 'b']转换成{'a':0, 'b':1}的形式
		@param para_list: 列表，里面是每个列对应的字段名
		@return: 字典，里面是字段名和位置的映射
		"""
        res_dict = {}
        idx = 0
        while idx < len(para_list):
            res_dict[str(para_list[idx]).strip()] = idx
            idx += 1
        return res_dict
    
    @staticmethod
    def map_fields_list_schema(fields, list_schema):
        """根据字段的模式，返回模式和数据值的对应值；例如 fields为['a','b','c'],schema为{'name', 'age'}，那么就返回{'name':'a','age':'b'}
		@param fields: 包含有数据的数组，一般是通过对一个Line String通过按照\t分割得到
		@param list_schema: 列名称的列表list
		@return: 词典，key是字段名称，value是字段值
		"""
        dict_schema = FileUtil.transform_list_to_dict(list_schema)
        return FileUtil.map_fields_dict_schema(fields, dict_schema)


@staticmethod
def map_fields_dict_schema(fields, dict_schema):
    """根据字段的模式，返回模式和数据值的对应值；例如 fields为['a','b','c'],schema为{'name':0, 'age':1}，那么就返回{'name':'a','age':'b'}
	@param fields: 包含有数据的数组，一般是通过对一个Line String通过按照\t分割得到
	@param dict_schema: 一个词典，key是字段名称，value是字段的位置；
	@return: 词典，key是字段名称，value是字段值
	"""
    pdict = {}
    for fstr, findex in dict_schema.iteritems():
        pdict[fstr] = str(fields[int(findex)])
    return pdict


