from flask import Blueprint, request, render_template, redirect, flash
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

addasset_bp = Blueprint('addasset', __name__)

@addasset_bp.route('/create/', methods=['GET', 'POST'])
def create():
    if request.method == 'GET':
        # Render the "add item" form
        return render_template('create.html', item_attributes=item_attributes)

    # Process submitted form
    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('create.html', item_attributes=item_attributes, error=error)

        # Create the Asset object
        item = Asset(**form_data)

        try:
            db.session.add(item)
            db.session.commit()
        except exc.IntegrityError as e:
            # Handle duplicate primary key or unique constraint errors
            primary_attrib = next((attrib for attrib in item_attributes if attrib.primary), None)
            if primary_attrib:
                error = f"An entry with {primary_attrib.display_name} '{form_data[primary_attrib.attrib_name]}' already exists."
            else:
                error = "An entry with the same primary key already exists."
            return render_template('create.html', item_attributes=item_attributes, error=error)
        except exc.StatementError as e:
            # Handle other database errors
            error = f"Database error: {str(e)}"
            return render_template('create.html', item_attributes=item_attributes, error=error)
        except Exception as e:
            # Handle unexpected errors
            error = f"An unexpected error occurred: {str(e)}"
            return render_template('create.html', item_attributes=item_attributes, error=error)

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