from flask import Blueprint, redirect, session, request, flash, url_for
from definitions.models import Asset, db
from functions.validate_values import validate_values
from config import item_attributes
import json

confirm_save_bp = Blueprint('confirm_save', __name__)

@confirm_save_bp.route('/confirm_save', methods=['POST'])
def confirm_save():
    # Check if assets data is present in the request
    if 'assets' not in request.form:
        flash("No assets data found in the request.", "error")
        return redirect(url_for('uploadcsv.upload_file'))

    try:
        # Parse the JSON data from the form
        edited_assets = json.loads(request.form['assets'])
    except json.JSONDecodeError:
        flash("Invalid JSON data in the request.", "error")
        return redirect(url_for('uploadcsv.upload_file'))

    # Validate each asset
    errors = []
    for i, asset_data in enumerate(edited_assets, start=1):
        error = validate_values(asset_data)
        if error:
            errors.append(f"Row {i}: {error}")

    if errors:
        # If there are validation errors, flash them and redirect back to the preview page
        for error in errors:
            flash(error, "error")
        return redirect(url_for('uploadcsv.upload_file'))

    # Save validated assets to the database
    for asset_data in edited_assets:
        asset = Asset(**{
            attrib.attrib_name: asset_data[attrib.attrib_name]
            for attrib in item_attributes
        })
        db.session.add(asset)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        flash(f"Error saving data to the database: {str(e)}", "error")
        return redirect(url_for('uploadcsv.upload_file'))

    # Clear session data after successful insertion
    session.pop('assets', None)
    return redirect('/viewall')