# Define your custom views here or overwrite the default views. Default
# CRUD operations are generated by the ringo frameworkd.

import logging
import mimetypes

from ringo.views.base import create, update, read
from ringo.views.base import web_action_view_mapping

log = logging.getLogger(__name__)


def save_file(request, item):
    """Helper function which is called after the validation of the form
    succeeds. The function will get the data from the file from the
    request and set it in the model including size and mime type.
    Addiotionally it will set the filename based on the uploaded file if
    no other name is given."""
    try:
        #  FIXME: Use global helper method for this??? (ti) <2015-01-31
        #  16:49>
        # Rewind file
        request.POST.get('file').file.seek(0)
        data = request.POST.get('file').file.read()
        filename = request.POST.get('file').filename
        item.data = data
        item.size = len(data)
        item.mime = mimetypes.guess_type(filename)[0]
        if not request.POST.get('name'):
            item.name = filename
    except AttributeError:
        # Will be raised if the user submits no file.
        pass
    return item


def create_(request):
    return create(request, callback=save_file)


def update_(request):
    return update(request, callback=save_file)


def download(request):
    result = read(request)
    item = result['item']
    response = request.response
    response.content_type = str(item.mime)
    extension = mimetypes.guess_extension(item.mime)
    label = item.get_value("name", expand=True)
    filename = "%(filename)s%(suffix)s" % {"filename": label,
                                           "suffix": extension}
    response.content_disposition = 'attachment; filename="%s"' % filename
    response.body = item.data
    return response


web_action_view_mapping["default"]["download"] = download
# FIXME: 2016-04-19: Tried to overwrite the routing with view_config but
# without success. Looked in ringo_printtemplates how it is done there.
web_action_view_mapping["files"] = {}
web_action_view_mapping["files"]["create"] = create_
web_action_view_mapping["files"]["update"] = update_
web_action_view_mapping["files"]["download"] = download
