# -*- coding: utf-8 -*-
#
# w.c.s. - web application for online forms
# Copyright (C) 2005-2013  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import zipfile

try:
    import elementtree.ElementTree as ET
except ImportError:
    try:
        import xml.etree.ElementTree as ET
    except ImportError:
        ET = None


OFFICE_NS = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
TABLE_NS = 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'
TEXT_NS = 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'
XLINK_NS = 'http://www.w3.org/1999/xlink'


class Workbook(object):
    def __init__(self, encoding='utf-8'):
        self.sheets = []
        self.encoding = encoding

    def add_sheet(self, name):
        sheet = WorkSheet(self, name)
        self.sheets.append(sheet)
        return sheet

    def get_node(self):
        root = ET.Element('{%s}document-content' % OFFICE_NS)
        ET.SubElement(root, '{%s}scripts' % OFFICE_NS)
        ET.SubElement(root, '{%s}font-face-decls' % OFFICE_NS)
        body = ET.SubElement(root, '{%s}body' % OFFICE_NS)
        spreadsheet = ET.SubElement(body, '{%s}spreadsheet' % OFFICE_NS)
        for sheet in self.sheets:
            spreadsheet.append(sheet.get_node())
        return root

    def get_data(self):
        return ET.tostring(self.get_node(), 'utf-8')

    def save(self, output):
        z = zipfile.ZipFile(output, 'w')
        z.writestr('content.xml', self.get_data())
        z.writestr('mimetype', 'application/vnd.oasis.opendocument.spreadsheet')
        z.writestr('META-INF/manifest.xml', '''<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
 <manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>
 <manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml"/>
 <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
 <manifest:file-entry manifest:full-path="META-INF/manifest.xml" manifest:media-type="text/xml"/>
 <manifest:file-entry manifest:full-path="mimetype" manifest:media-type="text/plain"/>
</manifest:manifest>''')
        z.writestr('styles.xml', '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0">
</office:document-styles>''')
        z.close()


class WorkSheet(object):
    def __init__(self, workbook, name):
        self.cells = {}
        self.name = name
        self.workbook = workbook

    def write(self, row, column, value, hint=None):
        if not row in self.cells:
            self.cells[row] = {}
        self.cells[row][column] = WorkCell(self, value, hint=hint)

    def get_node(self):
        root = ET.Element('{%s}table' % TABLE_NS)
        root.attrib['{%s}name' % TABLE_NS] = self.name
        ET.SubElement(root, '{%s}table-column' % TABLE_NS)
        for i in range(0, max(self.cells.keys())+1):
            row = ET.SubElement(root, '{%s}table-row' % TABLE_NS)
            for j in range(0, max(self.cells.get(i).keys())+1):
                cell = self.cells.get(i, {}).get(j, None)
                if not cell:
                    ET.SubElement(row, '{%s}table-cell' % TABLE_NS)
                else:
                    row.append(cell.get_node())
        return root


class WorkCell(object):
    def __init__(self, worksheet, value, hint=None):
        if type(value) is not unicode:
            value = unicode(value, 'utf-8')
        self.value = value
        self.worksheet = worksheet
        self.hint = hint

    def get_node(self):
        root = ET.Element('{%s}table-cell' % TABLE_NS)
        root.attrib['{%s}value-type' % OFFICE_NS] = 'string'
        p = ET.SubElement(root, '{%s}p' % TEXT_NS)
        if self.hint == 'uri':
            base_filename = self.value.split('/')[-1]
            if base_filename:
                a = ET.SubElement(p, '{%s}a' % TEXT_NS)
                a.attrib['{%s}href' % XLINK_NS] = self.value
                a.text = base_filename
                return root
        p.text = self.value
        return root
