import flask; from flask import request
import os
import subprocess
import traceback
import urllib.parse

from voussoirkit import cacheclass
from voussoirkit import flasktools
from voussoirkit import pathclass
from voussoirkit import stringtools
from voussoirkit import vlogging

log = vlogging.get_logger(__name__)

import etiquette

from .. import common
from .. import helpers

site = common.site
session_manager = common.session_manager
photo_download_zip_tokens = cacheclass.Cache(maxlen=100)

# Individual photos ################################################################################

@site.route('/photo/<photo_id>')
def get_photo_html(photo_id):
    photo = common.P_photo(photo_id, response_type='html')
    return common.render_template(request, 'photo.html', photo=photo)

@site.route('/photo/<photo_id>.json')
def get_photo_json(photo_id):
    photo = common.P_photo(photo_id, response_type='json')
    photo = photo.jsonify()
    photo = flasktools.json_response(photo)
    return photo

@site.route('/file/<photo_id>')
@site.route('/file/<photo_id>/<basename>')
def get_file(photo_id, basename=None):
    photo_id = photo_id.split('.')[0]
    photo = common.P.get_photo(photo_id)

    do_download = request.args.get('download', False)
    do_download = stringtools.truthystring(do_download)

    use_original_filename = request.args.get('original_filename', False)
    use_original_filename = stringtools.truthystring(use_original_filename)

    if do_download:
        if use_original_filename:
            download_as = photo.basename
        else:
            download_as = photo.id + photo.dot_extension

        download_as = etiquette.helpers.remove_path_badchars(download_as)
        download_as = urllib.parse.quote(download_as)
        response = flask.make_response(common.send_file(photo.real_path.absolute_path))
        response.headers['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % download_as
        return response
    else:
        return common.send_file(photo.real_path.absolute_path, override_mimetype=photo.mimetype)

@site.route('/thumbnail/<photo_id>')
def get_thumbnail(photo_id):
    photo_id = photo_id.split('.')[0]
    photo = common.P_photo(photo_id, response_type='html')
    if photo.thumbnail:
        path = photo.thumbnail
    else:
        flask.abort(404, 'That file doesnt have a thumbnail')
    return common.send_file(path)

# Photo create and delete ##########################################################################

@site.route('/photo/<photo_id>/delete', methods=['POST'])
def post_photo_delete(photo_id):
    print(photo_id)
    photo = common.P_photo(photo_id, response_type='json')
    delete_file = request.form.get('delete_file', False)
    delete_file = stringtools.truthystring(delete_file)
    photo.delete(delete_file=delete_file, commit=True)
    return flasktools.json_response({})

# Photo tag operations #############################################################################

def post_photo_add_remove_tag_core(photo_ids, tagname, add_or_remove):
    if isinstance(photo_ids, str):
        photo_ids = stringtools.comma_space_split(photo_ids)

    photos = list(common.P_photos(photo_ids, response_type='json'))
    tag = common.P_tag(tagname, response_type='json')