# coding: utf-8
from flask import send_file, render_template, flash, redirect, url_for, request, Blueprint, current_app, abort, g
from flask_login import login_required, current_user
from webinterface import db
from webinterface.models.documentos import Documento

from werkzeug.utils import secure_filename

def ingest_file():
	import datetime
	import hashlib
	import os
	from shutil import copyfile
	from tempfile import NamedTemporaryFile
	# for key, values in request.form.items():
	#     current_app.logger.info('request-form: {}: {}'.format(key, values))
	#
	# for key, values in request.files.items():
	#     current_app.logger.info('request-file: {}: {}'.format(key, values))

	uuid_nill = "00000000000000000000000000000000"
	try:
		if len(request.form['currenthash']) < 32:
			currenthash = uuid_nill
		else:
			currenthash = request.form['currenthash']
	except Exception as e:
		currenthash = uuid_nill

	previtem = Documento.query.filter_by(hash=currenthash).one_or_none()

	sha1 = hashlib.sha1()
	newdocs = None

	if 'documento' in request.files and len(request.files['documento'].filename) > 0:
		uploaded_file = request.files['documento']
#		current_app.logger.info('Archivo subido: procesando {}'.format(uploaded_file.filename))
		fsize = 0
		with NamedTemporaryFile() as tmp:
			try:
				BUF_SIZE = 65536
				uploaded_file.save(tmp.name)
				fsize = os.path.getsize(tmp.name)
#				current_app.logger.debug('Archivo subido: Tamaño {} bytes'.format(fsize))
				with open(tmp.name, 'rb') as f:
					while True:
						data = f.read(BUF_SIZE)
						if not data:
							break
						sha1.update(data)
#				current_app.logger.debug('Archivo subido: hash {}'.format(sha1.hexdigest()[:32]))

			except Exception as e:
#				current_app.logger.error('Error leyendo el archivo: Name({}), Error({})'.format(uploaded_file.filename, str(e)))
				return (None, None)
			else:
				item = Documento.query.filter_by(hash=sha1.hexdigest()[:32]).one_or_none()
				if item is None:
					name = secure_filename(uploaded_file.filename)
					item = Documento(hash=sha1.hexdigest()[:32], nombre=name, descripcion=request.form['descripcion'].strip(), tamano=fsize, autorid=current_user.id, reemplazahash=previtem.hash)
					db.session.add(item)
					db.session.commit()
					try:
#                       current_app.logger.debug('Directorio:  {}'.format(os.path.abspath(item.get_dir())))
						os.makedirs(os.path.abspath(item.get_dir()), exist_ok=True)
#                       current_app.logger.debug('Archivo: {}'.format(os.path.abspath(item.get_file())))
						copyfile(tmp.name, os.path.abspath(item.get_file()))

					except Exception as e:
						return (None, None)
				else:
					if not os.path.exists(os.path.abspath(item.get_file())):
						try:
	#                           current_app.logger.info('Archivo: {}'.format(os.path.abspath(item.get_file())))
							item.name 			= secure_filename(uploaded_file.filename)
							item.reemplazahash 	= previtem.hash
							copyfile(tmp.name, os.path.abspath(item.get_file()))
							db.session.commit()
						except Exception as e:
							db.session.rollback()
							current_app.logger.error('Error al guardar el archivo: Name({}), Error({})'.format(uploaded_file.filename, str(e)))
							return (None, None)

#							current_app.logger.info('Archivo subido: guardado {}'.format(item.get_file()))
	elif previtem.tamano == 0 and len(request.form['url']) > 5:
		sha1.update(request.form['url'].strip().encode('utf-8'))
		item = Documento.query.filter_by(hash=sha1.hexdigest()[:32]).one_or_none()
		if item is None:
			item = Documento(hash=sha1.hexdigest()[:32], nombre=request.form['url'].strip(), descripcion=request.form['descripcion'].strip(), tamano=0, autorid=current_user.id, reemplazahash=previtem.hash)
			db.session.add(item)
		else:
			item.descripcion=request.form['descripcion'].strip()
		db.session.commit()

	elif currenthash != uuid_nill:
		previtem.descripcion = request.form['descripcion']
		db.session.commit()
		return (previtem, None)
	else:
		return (None, None)

	return (item, previtem)
