from apps.product.models import (
    Quota,
    QuotaDistribution,
    Organization,
    QuotaPriceCalculationItems,
    QuotaFinalPriceTypes
)
from apps.pos_device.models import Device, StakeHolderShareAmount
import typing


def pos_organizations_sharing_information(
        device: Device,
        quota: Quota = None,
        distribution: QuotaDistribution = None,
        owner_org: Organization = None
) -> typing.Any:
    """
    pos sharing organizations' information,
    device have multiple organizations (sub_accounts) for sharing money
    """
    stake_holders = device.stake_holders.select_related('broker', 'organization').filter(default=False)

    sharing_information_list = []
    for item in stake_holders:
        if item.broker and not owner_org.type.name == 'AGC':  # if stakeholder is not an agency, it is a broker
            sharing_information_list.append({
                "organization_name": item.organization.name,
                "bank_account": {
                    "credit_card": item.organization.bank_information.first().card,
                    "sheba": item.organization.bank_information.first().sheba,
                    "account": item.organization.bank_information.first().account,
                } if item.organization.bank_information.exists() else {},
                "broker": item.broker.name if item.broker else None,
                "amount": quota.broker_values.filter(
                    broker=item.broker
                ).first().value if quota and item.broker else None,

                # """
                # if we will need to get agencies share amount, we can use this bellow code
                #
                # # item.holders_share_amount.filter(quota_distribution=distribution).first().share_amount
                # # if item.holders_share_amount.filter(quota_distribution=distribution).exists() else None
                # """

                "default_account": item.default
            })

    # if device owner is an agency organization
    if owner_org.type.name == 'AGC':
        sharing_information_list.append({
            "organization_name": owner_org.parent_organization.name,
            "bank_account": {
                "credit_card": owner_org.parent_organization.bank_information.first().card,
                "sheba": owner_org.parent_organization.bank_information.first().sheba,
                "account": owner_org.parent_organization.bank_information.first().account,
            } if owner_org.parent_organization.bank_information.exists() else {},
            "amount": quota.pricing_items.get(
                name='base_price'
            ) if quota.pricing_items.filter(
                name='base_price'
            ) else None,
            "default_account": True
        })

    return sharing_information_list
