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

addasset_bp = Blueprint('addasset', __name__)

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

    # 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('item_form.html', item_attributes=item_attributes, item=None, error=error, brandingconfig=BrandingConfig)

        # 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('item_form.html', item_attributes=item_attributes, item=None, 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_attributes=item_attributes, item=None, 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_attributes=item_attributes, item=None, error=error, brandingconfig=BrandingConfig)

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