# -*- coding: utf-8 -*-
from flask import after_this_request, redirect, render_template, request, send_file, url_for
from os import remove
from os.path import join
import logging
from werkzeug.utils import secure_filename
from camp_app import app
from camp_builder.builder import campaign_builder


logger = logging.getLogger(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file_ = request.files['file']
        task_path = join(app.config['UPLOAD_FOLDER'], secure_filename(file_.filename))
        file_.save(task_path)

        return redirect(url_for('campaigns', task_path=task_path, zip_path=campaign_builder(task_path)))

    return render_template('index.html')


@app.route('/campaigns')
def campaigns():
    task_path = request.args['task_path']
    remove(task_path)

    zip_path = request.args['zip_path']

    @after_this_request
    def remove_file(response):
        remove(zip_path)
        return response

    return send_file(zip_path, as_attachment=True)
