from flask import Blueprint, request, render_template, redirect
from definitions.models import Asset, db
from config import item_attributes
from sqlalchemy import exc  # Import exc for database exceptions
from functions.validate_values import validate_values  # Form validation
from functions.auth import login_required
from config import BrandingConfig

update_bp = Blueprint('editasset', __name__)

@update_bp.route('/update/<string:primary_value>/', methods=['GET', 'POST'])
@login_required
def update(primary_value):
    # Identify the primary attribute
    primary_attrib = next((attrib for attrib in item_attributes if attrib.primary), None)
    if not primary_attrib:
        return "Primary attribute not defined in configuration."

    # Fetch the item using the primary attribute
    item = Asset.query.filter_by(**{primary_attrib.attrib_name: primary_value}).first()
    if not item:
        return f"{primary_attrib.display_name} '{primary_value}' not found."

    if request.method == 'GET':
        # Render the update form with the current item data
        return render_template('item_form.html', item=item, item_attributes=item_attributes, brandingconfig=BrandingConfig)

    if request.method == 'POST':
        # Get data from form
        form_data = {attrib.attrib_name: request.form.get(attrib.attrib_name) for attrib in item_attributes}

        # Form validation
        error = validate_values(form_data)
        if error:
            return render_template('item_form.html', item=item, item_attributes=item_attributes, error=error, brandingconfig=BrandingConfig)

        # Update the item with the new data
        for attrib in item_attributes:
            setattr(item, attrib.attrib_name, form_data[attrib.attrib_name])

        try:
            db.session.commit()
        except exc.IntegrityError:
            # Handle duplicate primary key or unique constraint errors
            error = f"An entry with {primary_attrib.display_name} '{form_data[primary_attrib.attrib_name]}' already exists."
            return render_template('item_form.html', item=item, item_attributes=item_attributes, error=error, brandingconfig=BrandingConfig)
        except exc.StatementError as e:
            # Handle other database errors
            error = f"Database error: {str(e)}"
            return render_template('item_form.html', item=item, item_attributes=item_attributes, error=error, brandingconfig=BrandingConfig)
        except Exception as e:
            # Handle unexpected errors
            error = f"An unexpected error occurred: {str(e)}"
            return render_template('item_form.html', item=item, item_attributes=item_attributes, error=error, brandingconfig=BrandingConfig)

        # Redirect to /viewall on success
        return redirect('/viewall')