from flask import Flask, request, send_file, jsonify
from flask_cors import CORS
import io
from PyPDF2 import PdfReader, PdfWriter

app = Flask(__name__)
CORS(app)

@app.route('/custom-route/', methods=['POST'])
def custom_route():
    if 'pdfFile' not in request.files or 'password' not in request.form:
        return jsonify({"error": "No file part or password in the request"}), 400

    file = request.files['pdfFile']
    password = request.form['password']

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    try:
        # Read the uploaded PDF file
        pdf_reader = PdfReader(file)
        pdf_writer = PdfWriter()

        for page in pdf_reader.pages:
            pdf_writer.add_page(page)

        # Set the password
        pdf_writer.encrypt(password)

        # Write the protected PDF to a BytesIO object
        protected_pdf_io = io.BytesIO()
        pdf_writer.write(protected_pdf_io)
        protected_pdf_io.seek(0)

        return send_file(protected_pdf_io, as_attachment=True, download_name="protected_file.pdf", mimetype='application/pdf')
    
    except Exception as e:
        app.logger.error(f"Error processing the file: {e}")
        return jsonify({"error": str(e)}), 500
        
        
@app.route('/test', methods=['GET'])
def fnc():
    return "hello dremerz yes its working"
    
@app.route('/', methods=['GET'])
def fn():
    return "hello dremerz"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

