"""Recorded history is distinct from operationally selectable ownership."""
from apps.customers.models import Customer
from apps.organization.models import Company
from .models import CustomerDeviceRelationship as Relationship, Device


def _saved(obj, model):
    return isinstance(obj, model) and not obj._state.adding and obj._state.db == "default"


def device_ownership_history(device):
    rows = Relationship.objects.select_related("customer__company", "device__product_model__brand")
    return rows.filter(device_id=device.pk, relationship_type="OWNER") if _saved(device, Device) else rows.none()


def current_ownership_relationship(device):
    return device_ownership_history(device).filter(ended_at__isnull=True).first()


def current_device_owner(device):
    row = current_ownership_relationship(device)
    return row.customer if row else None


def _operational(**filters):
    return Device.objects.filter(is_active=True, customer_relationships__relationship_type="OWNER",
        customer_relationships__ended_at__isnull=True, customer_relationships__customer__is_active=True,
        customer_relationships__customer__company__is_active=True, **filters).select_related("product_model__brand", "product_variant")


def currently_owned_devices(customer):
    return _operational(customer_relationships__customer_id=customer.pk) if _saved(customer, Customer) else Device.objects.none()


def currently_owned_devices_for_company(company):
    return _operational(customer_relationships__customer__company_id=company.pk) if _saved(company, Company) else Device.objects.none()
