#!/bin/env python3
# -*- coding: utf-8 -*-
#    TOMUSS: The Online Multi User Simple Spreadsheet
#    Copyright (C) 2015 Thierry EXCOFFIER, Universite Claude Bernard
#
#    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, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    Contact: Thierry.EXCOFFIER@bat710.univ-lyon1.fr

from .columnfill import ColumnFill
from .. import plugin
from .. import document
from ..COLUMN_TYPES import upload

class ColumnUploadZip(ColumnFill):
    name = 'upload_zip'
    action = 'upload_zip'

def filename_from_comment(txt, png=False):
    if png:
        return 'doc.png'
    txt = txt.replace("; ", ";").split(' ',1)
    if len(txt) != 2:
        return 'unknown'
    return txt[1].replace(":", "_").replace("/", "_").replace("\\", "_")

def upload_zip(server, png=False):
    """Upload one ZIP file to split across the table cell"""
    import zipfile
    import os
    import tempfile
    table = document.table(server.the_year, server.the_semester,
                           server.the_ue, create=False)
    if not table:
        raise ValueError("Can't find table") # pragma: no cover
    column = table.columns.from_id(server.the_path[0])
    dirname = upload.container_path(column)
    f, name = tempfile.mkstemp()
    zf = zipfile.ZipFile(os.fdopen(f, "wb"),
                         mode="w", compression=zipfile.ZIP_DEFLATED)
    if len(server.the_path) == 3 and server.the_path[1] == '*':
        lin_ids = tuple(table.lines)
    else:
        lin_ids = server.the_path[1:-1]
    done = set()
    try:
        # Create the ZIP file on disk
        for lin_id in lin_ids:
            if lin_id not in table.lines:
                continue
            line = table.lines[lin_id]
            filename = os.path.join(dirname, lin_id)
            if png:
                filename += '.png'
            if not line[column.data_col].comment or not os.path.exists(filename):
                # Search the uploaded file in the other group-member lines
                for lin_id, line in column.lines_of_the_group(line): # pylint: disable=redefined-outer-name
                    filename = os.path.join(dirname, lin_id)
                    if line[column.data_col].comment and os.path.exists(filename):
                        break
                else:
                    continue
            if filename in done:
                continue
            done.add(filename)
            zf.write(
                filename,
                "%d_%s_%s_%s" % (table.year, table.semester, table.ue,
                                column.title.replace('/','_'))
                + '/' + line[0].value +"#"+ line[1].value +'_'+ line[2].value
                + '_' + filename_from_comment(line[column.data_col].comment, png=png)
            )
        zf.close()
        # Send the ZIP file
        f = open(name, "rb")
        while True:
            c = f.read(1024)
            if c == b'':
                break
            else:
                server.the_file.write(c)
        f.close()
    finally:
        os.unlink(name)
        del f
        del zf

plugin.Plugin('upload_zip', '/{Y}/{S}/{U}/upload_zip/{*}',
              function=upload_zip, launch_thread = True,
              mimetype="application/zip", group='staff'
          )
