from io import BytesIO
from flask import (
    render_template,
    Blueprint,
    flash,
    send_file,
    request,
    Response
    )
from sesivacka.dashboard.forms import FileForm
from PyPDF2 import PdfFileReader, PdfFileWriter

dashboard_blueprint = Blueprint(
    'dashboard',
    __name__,
    template_folder='templates'

)

@dashboard_blueprint.route('/', methods=['GET', 'POST'])
def index():
    """
    Render dashboard page.
    :return: rendered page
    """
    form = FileForm()
    if form.validate_on_submit():
        pdf_writer = PdfFileWriter()
        files = []
        for item in ('first_file', 'second_file'):
            files.extend(request.files.getlist(item))
        for pdf_stream in files:
                pdf_reader = PdfFileReader(pdf_stream)
                flash(pdf_reader.getDocumentInfo())
                for page in range(pdf_reader.getNumPages()):
                    pdf_writer.addPage(pdf_reader.getPage(page))
        pdf = BytesIO()
        pdf_writer.write(pdf)
        flash(len(pdf.getvalue()))
        pdf.seek(0)
        # output_file = wrap_file(pdf.getvalue())
        return send_file(
            pdf,
            mimetype='application/pdf',
            as_attachment=True,
            attachment_filename=files[0].filename
        )



    return render_template(
        'dashboard.jinja.html',
        form=form
    )