from sqlalchemy.sql.expression import func

from app import db
from app.dao.dao_utils import VersionOptions, autocommit, version_class
from app.models import Domain, Organization, Service, User


def dao_get_organizations():
    return Organization.query.order_by(
        Organization.active.desc(), Organization.name.asc()
    ).all()


def dao_count_organizations_with_live_services():
    return (
        db.session.query(Organization.id)
        .join(Organization.services)
        .filter(
            Service.active.is_(True),
            Service.restricted.is_(False),
            Service.count_as_live.is_(True),
        )
        .distinct()
        .count()
    )


def dao_get_organization_services(organization_id):
    return Organization.query.filter_by(id=organization_id).one().services


def dao_get_organization_live_services(organization_id):
    return Service.query.filter_by(
        organization_id=organization_id, restricted=False
    ).all()


def dao_get_organization_by_id(organization_id):
    return Organization.query.filter_by(id=organization_id).one()


def dao_get_organization_by_email_address(email_address):
    email_address = email_address.lower().replace(".gsi.gov.uk", ".gov.uk")

    for domain in Domain.query.order_by(func.char_length(Domain.domain).desc()).all():
        if email_address.endswith(
            "@{}".format(domain.domain)
        ) or email_address.endswith(".{}".format(domain.domain)):
            return Organization.query.filter_by(id=domain.organization_id).one()

    return None


def dao_get_organization_by_service_id(service_id):
    return (
        Organization.query.join(Organization.services).filter_by(id=service_id).first()
    )


@autocommit
def dao_create_organization(organization):
    db.session.add(organization)


@autocommit
def dao_update_organization(organization_id, **kwargs):
    domains = kwargs.pop("domains", None)
    num_updated = Organization.query.filter_by(id=organization_id).update(kwargs)

    if isinstance(domains, list):
        Domain.query.filter_by(organization_id=organization_id).delete()
        db.session.bulk_save_objects(
            [
                Domain(domain=domain.lower(), organization_id=organization_id)
                for domain in domains
            ]
        )

    organization = Organization.query.get(organization_id)
    if "organization_type" in kwargs:
        _update_organization_services(
            organization, "organization_type", only_where_none=False
        )

    if "email_branding_id" in kwargs:
        _update_organization_services(organization, "email_branding")

    return num_updated


@version_class(
    VersionOptions(Service, must_write_history=False),
)
def _update_organization_services(organization, attribute, only_where_none=True):
    for service in organization.services:
        if getattr(service, attribute) is None or not only_where_none:
            setattr(service, attribute, getattr(organization, attribute))
        db.session.add(service)


@autocommit
@version_class(Service)
def dao_add_service_to_organization(service, organization_id):
    organization = Organization.query.filter_by(id=organization_id).one()

    service.organization_id = organization_id
    service.organization_type = organization.organization_type

    db.session.add(service)


def dao_get_users_for_organization(organization_id):
    return (
        db.session.query(User)
        .join(User.organizations)
        .filter(Organization.id == organization_id, User.state == "active")
        .order_by(User.created_at)
        .all()
    )


@autocommit
def dao_add_user_to_organization(organization_id, user_id):
    organization = dao_get_organization_by_id(organization_id)
    user = User.query.filter_by(id=user_id).one()
    user.organizations.append(organization)
    db.session.add(organization)
    return user


@autocommit
def dao_remove_user_from_organization(organization, user):
    organization.users.remove(user)
