import io
import zipfile
import xml.etree.ElementTree as ET

from django.conf import settings


def login(app, user, path=None, password=None):
    if path:
        login_page = app.get(path)
    else:
        login_page = app.get(settings.LOGIN_URL)
    login_page = login_page.maybe_follow()
    form = login_page.form
    form.set('username', user.username if hasattr(user, 'username') else user)
    # password is supposed to be the same as username
    form.set('password', password or user.username)
    response = form.submit(name='login-password-submit').follow(expect_errors=True)
    if path:
        assert response.request.path == path
    assert '_auth_user_id' in app.session
    assert str(app.session['_auth_user_id']) == str(user.id)
    return response


def get_table(response):
    table = []

    for tr in response.pyquery('table tr'):
        row = []
        table.append(row)
        for td in tr.findall('td'):
            row.append((td.text or '').strip())
    return table


def xml_node_text_content(node):
    '''Extract text content from node and all its children. Equivalent to
       xmlNodeGetContent from libxml.'''

    if node is None:
        return ''

    def helper(node):
        s = []
        if node.text:
            s.append(node.text)
        for child in node:
            s.extend(helper(child))
            if child.tail:
                s.append(child.tail)
        return s
    return u''.join(helper(node))


def get_ods_document(response):
    return ET.fromstring(zipfile.ZipFile(io.BytesIO(response.content)).read('content.xml'))


def get_ods_table(response):
    from bijoe.visualization.ods import TABLE_NS

    root = get_ods_document(response)
    table = []
    for row_node in root.findall('.//{%s}table-row' % TABLE_NS):
        row = []
        table.append(row)
        for cell_node in row_node.findall('.//{%s}table-cell' % TABLE_NS):
            row.append(xml_node_text_content(cell_node))
    return table
