#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter web page
    name:upload.py
    author:rabin
"""
from __load__ import *
from datetime import *
import os
import uuid
#from PIL import Image

class upload_path(Load):
 	@Web.auth
	@Web.setting
	def post(self, *args, **kwargs):
		url = self.request.protocol + "://" + self.request.host
		url = 'http://admin.nongxiaohe.com'
		file_metas = self.request.files["file"]
		#crop = self.input('crop', 1)
		crop = False

		# print(file_metas)
		day = str(date.today())
		day = day.split('-')
		for meta in file_metas:
			#meta['filename']
			file_name =  str(uuid.uuid5(uuid.uuid1(), 'file'))
			file_path = day[0] + '/' + day[1] + '/' + day[2]
			file_path = File.mkdirs(os.path.join(Demeter.path, 'runtime','upload', file_path)) + '/' + Demeter.md5(file_name) + '.jpg'
			with open(file_path, 'wb') as up:
				up.write(meta['body'])
		if crop:
			#裁图类型,暂时居中裁图
			file_path = cropImage(file_path)
		#self.out('yes', {'src':url + file_path.replace(Demeter.path + 'runtime', '')})
		file = url + file_path.replace(Demeter.path + 'runtime', '')
		self.write({'state':True,'file_path':file, 'src':file})

def cropImage(file):
	img = Image.open(file)
	width = img.size[0]
	height = img.size[1]
	size = 0
	x = 0
	y = 0
	if width == height:
		return file
	elif width < height:
		size = width
		x = 0
		y = (height-width)/2
	else:
		size = height
		x = (width-height)/2
		y = 0
	#img.thumbnail((500, 500))
	crop = img.crop((x, y, size+x, size+y))
	file = file + '_crop_center.jpg'
	crop.save(file)
	return file