# coding=utf8
from django.http import HttpResponse
from xlwt.Workbook import Workbook


def _init_ws(ws, opts):
    for index, opt in enumerate(opts):
        ws.write(0, index, opt.get('title'))
        ws.col(index).width = opt.get('width')


def _write_ws_instance(ws, index, instance, opts):
    for _index, opt in enumerate(opts):
        if isinstance(instance, dict):
            field = instance.get(opt.get('field'))
        else:
            field = getattr(instance, opt.get('field'))
        if callable(field):
            value = field()
        elif callable(opt.get('format')):
            value = opt.get('format')(field)
        else:
            value = field
        ws.write(index, _index, value)


def _write_ws(ws, instances, opts, is_init_ws):
    for index, instance in enumerate(instances):
        if is_init_ws:
            index += 1
        _write_ws_instance(ws, index, instance, opts)


def export_excel(instances, configs=None, write_ws=None, init_ws=None, encoding='utf-8'):
    if not configs:
        raise Exception('服务器异常')
    write_ws_ = write_ws or _write_ws
    if write_ws_ and not callable(write_ws_):
        raise Exception('服务器异常')

    init_ws_ = init_ws or _init_ws
    if init_ws_ and not callable(init_ws_):
        raise Exception(u'服务器异常')
    w = Workbook(encoding=encoding)
    ws = w.add_sheet(configs.get('sheet_name'))

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s' % configs.get('file_name')

    is_init_ws = False
    if init_ws_:
        is_init_ws = True
        init_ws_(ws, configs.get('opts'))

    write_ws_(ws, instances, configs.get('opts'), is_init_ws)

    w.save(response)
    return response
