from flask import current_app, url_for
from sqlalchemy.exc import SQLAlchemyError

from common.extensions import db
from common.models.user import Partner, Tenant, PartnerService


def get_partners_list_view():
    """Genereer de partners lijst-weergave configuratie"""
    # Haal alle partners op met hun tenant informatie
    query = (db.session.query(
        Partner.id,
        Partner.active,
        Tenant.name.label('name')
    ).join(Tenant, Partner.tenant_id == Tenant.id).order_by(Partner.id))

    try:
        all_partners = query.all()

        # Bereid data voor voor Tabulator
        data = []
        for partner in all_partners:
            data.append({
                'id': partner.id,
                'name': partner.name,
                'active': partner.active
            })

        # Kolomdefinities
        columns = [
            {'title': 'ID', 'field': 'id', 'width': 80},
            {'title': 'Name', 'field': 'name'},
            {'title': 'Active', 'field': 'active', 'formatter': 'tickCross'}
        ]

        actions = [
            {'value': 'set_session_partner', 'text': 'Set Session Partner', 'class': 'btn-primary', 'requiresSelection': True},
            {'value': 'edit_partner', 'text': 'Edit Partner', 'class': 'btn-primary', 'requiresSelection': True},
            {'value': 'create_partner', 'text': 'Register Partner', 'class': 'btn-success', 'position': 'right', 'requiresSelection': False},
        ]

        initial_sort = [{'column': 'id', 'dir': 'asc'}]

        return {
            'title': 'Partners',
            'data': data,
            'columns': columns,
            'actions': actions,
            'initial_sort': initial_sort,
            'table_id': 'partners_table',
            'form_action': url_for('partner_bp.handle_partner_selection'),
            'description': 'Manage partners'
        }

    except SQLAlchemyError as e:
        current_app.logger.error(f"Error bij het ophalen van partners: {str(e)}")
        return {
            'title': 'Partners',
            'data': [],
            'columns': [],
            'actions': [],
            'initial_sort': [],
            'table_id': 'partners_table',
            'form_action': url_for('partner_bp.handle_partner_selection'),
            'description': 'Er is een fout opgetreden bij het ophalen van partners. Probeer het later opnieuw.'
        }


def get_partner_services_list_view(partner_id):
    """Genereer de partner services lijst-weergave configuratie"""
    # Haal alle partner services op voor deze partner
    query = PartnerService.query.filter(PartnerService.partner_id == partner_id)

    try:
        all_partner_services = query.all()

        # Bereid data voor voor Tabulator
        data = []
        for service in all_partner_services:
            data.append({
                'id': service.id,
                'name': service.name,
                'type': service.type,
                'type_version': service.type_version
            })

        # Kolomdefinities
        columns = [
            {'title': 'ID', 'field': 'id', 'width': 80},
            {'title': 'Name', 'field': 'name'},
            {'title': 'Type', 'field': 'type'},
            {'title': 'Version', 'field': 'type_version'}
        ]

        actions = [
            {'value': 'edit_partner_service', 'text': 'Edit Service', 'class': 'btn-primary', 'requiresSelection': True},
            {'value': 'add_partner_service_for_tenant', 'text': 'Assign to Tenant', 'class': 'btn-secondary', 'requiresSelection': True},
            {'value': 'create_partner_service', 'text': 'Register Service', 'class': 'btn-success', 'position': 'right', 'requiresSelection': False},
        ]

        initial_sort = [{'column': 'id', 'dir': 'asc'}]

        return {
            'title': 'Partner Services',
            'data': data,
            'columns': columns,
            'actions': actions,
            'initial_sort': initial_sort,
            'table_id': 'partner_services_table',
            'form_action': url_for('partner_bp.handle_partner_service_selection'),
            'description': 'Manage Partner Services'
        }

    except SQLAlchemyError as e:
        current_app.logger.error(f"Error bij het ophalen van partner services: {str(e)}")
        return {
            'title': 'Partner Services',
            'data': [],
            'columns': [],
            'actions': [],
            'initial_sort': [],
            'table_id': 'partner_services_table',
            'form_action': url_for('partner_bp.handle_partner_service_selection'),
            'description': 'Er is een fout opgetreden bij het ophalen van partner services. Probeer het later opnieuw.'
        }
