from flask import render_template, request, abort, flash, jsonify
from flask_uploads import configure_uploads, UploadSet, IMAGES
from pony import orm

from ..models import Attach, Record
from ..utils import generate_file_name


def init(app):
    @app.route('/', methods=['GET', 'POST'])
    def index():
        with orm.db_session:
            if request.method == 'POST':
                rec = Record(text=request.form['text'], ip=request.remote_addr)
                for attach in request.form.getlist('attach[]'):
                    try:
                        item = Attach[attach]
                        rec.attaches += item
                    except orm.core.ObjectNotFound:
                        abort(500)
                flash('Запись отправлена на модерацию!')

            data = {
                'moderation': orm.count(r for r in Record if r.status == 'NEW'),
                'published': orm.count(r for r in Record if r.status == 'APPROVED'),
                'total': orm.count(r for r in Record),
                'name': app.config['NAME'],
                'group': app.config['GROUP'],
                'base_url': request.host_url
            }

        return render_template('index.html', data=data)

    pictures = UploadSet('pictures', IMAGES)
    configure_uploads(app, pictures)

    @app.route('/upload', methods=['POST'])
    def upload():
        if 'picture' in request.files:
            file = request.files['picture']
            filename = pictures.save(file, name=generate_file_name(file))
            with orm.db_session:
                rec = Attach(filename=filename, ip=request.remote_addr)
            return jsonify({'url': pictures.url(filename), 'id': rec.id})
        abort(404)

    @app.route('/photo/<id>')
    def show(id):
        #//photo = Photo.load(id)
        #//if photo is None:
            #abort(404)
        #url = photos.url(photo.filename)
        #return render_template('show.html', url=url, photo=photo)
        pass
