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
from functions.auth import login_required

confirm_save_bp = Blueprint('confirm_save', __name__)

@confirm_save_bp.route('/confirm_save/', methods=['POST'])
@login_required
def confirm_save():
    # Retrieve mode from session
    mode = session.get('csv_mode')
    if mode not in ['import', 'edit']:
        flash("Invalid operation mode. Please try again.", "error")
        return redirect(url_for('uploadcsv.import_from_csv'))

    # 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.import_from_csv' if mode == 'import' else 'uploadcsv.edit_using_csv'))

    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.import_from_csv' if mode == 'import' else 'uploadcsv.edit_using_csv'))

    # 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.import_from_csv' if mode == 'import' else 'uploadcsv.edit_using_csv'))

    # Save validated assets to the database
    for asset_data in edited_assets:
        primary_attrib = next((attrib for attrib in item_attributes if attrib.primary), None)
        if not primary_attrib:
            flash("Primary attribute not defined in configuration.", "error")
            return redirect(url_for('uploadcsv.import_from_csv' if mode == 'import' else 'uploadcsv.edit_using_csv'))

        primary_value = asset_data[primary_attrib.attrib_name]
        asset = Asset.query.filter_by(**{primary_attrib.attrib_name: primary_value}).first()

        if asset:
            # Update existing asset
            for attrib in item_attributes:
                setattr(asset, attrib.attrib_name, asset_data[attrib.attrib_name])
        else:
            # Add new asset
            asset = Asset(**asset_data)
            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.import_from_csv' if mode == 'import' else 'uploadcsv.edit_using_csv'))

    # Clear session data after successful insertion
    session.pop('new_entries', None)
    session.pop('existing_entries', None)
    session.pop('invalid_entries', None)
    session.pop('csv_mode', None)
    return redirect('/viewall')