from ....base.firebase_collection import FirebaseCollectionBase
from .....utils import (DictUtils, init_class_kwargs, get_request_fields)
from .base_adgroup_fields import BaseAdGroupFieldsProps, STANDARD_FIELDS, BASE_ADGROUP_PICKABLE_FIELDS
from typing import Any
from dataclasses import dataclass
from adafri.utils import DateUtils
from ..ages import Ages
from ..genders import Genders
from ..devices import Devices
from google.cloud.firestore_v1.transforms import Sentinel
from datetime import datetime

def filter_request_fields(fields, default_fields = BASE_ADGROUP_PICKABLE_FIELDS):
    request_fields = get_request_fields(fields, default_fields, [default_fields[0]])
    if request_fields is None or bool(request_fields) is False:
        request_fields = [default_fields[0]]
    return request_fields



@dataclass(init=False)
class BaseAdGroup(FirebaseCollectionBase):
    id: str
    campaign_id: int
    name: str
    status: str
    ages: list[Ages]
    genders: list[Genders]
    devicesTargeted: list[Devices]
    devicesExcluded: list[Devices]
    is_removed: bool = False
    ad_group_id: int
    bid: float
    strategie: str
    owner: str
    provider: str
    clientCustomerId: str
    campaign_id_parent: str
    accountId: str
    createdAt: any
    createdBy: str
    api_version: str
    google_ads_ad_group: dict
    __baseFields =  BaseAdGroupFieldsProps

    def __init__(self, adgroup=None, collection_name=None, **kwargs):
        _adgroup = adgroup
        if type(adgroup) is str:
            _adgroup = {"id": adgroup}
        # if adgroup is not None:
        #     print('init first', adgroup['id'])
        (cls_object, keys, data_args) = init_class_kwargs(self, _adgroup, STANDARD_FIELDS, BaseAdGroupFieldsProps, collection_name, ['id'], **kwargs)
        super().__init__(**data_args);
        for key in keys:
            if key == "ages":
                setattr(self, key, Ages().fromListDict(cls_object[key], Ages))
            elif key == "genders":
                setattr(self, key, Genders().fromListDict(cls_object[key], Genders))
            elif key == "devicesTargeted":
                setattr(self, key, Devices().fromListDict(cls_object[key], Devices))
            elif key == "devicesExcluded":
                setattr(self, key, Devices().fromListDict(cls_object[key], Devices))
            elif key == "createdAt":
                createdAt = DateUtils.convert_firestore_timestamp_to_str(cls_object[key]);
                if isinstance(createdAt, Sentinel) is True:
                    createdAt = datetime.now().strftime('%Y-%m-%d %H:%M:%S');
                setattr(self, key, createdAt) 
            else:
                setattr(self, key, cls_object[key]) 


    @staticmethod
    def generate_model(_key_="default_value"):
        adgroup = {};
        props = BaseAdGroupFieldsProps
        for k in DictUtils.get_keys(props):
            adgroup[k] = props[k][_key_];
        return adgroup;
    def ages_to_list(self, ages: list[Ages] | None = None):
        if ages is None:
            return [];
        return Ages().toListDict(ages, None)
    def genders_to_list(self, genders: list[Genders] | None = None):
        if genders is None:
            return [];
        return Genders().toListDict(genders, None)
    def devices_to_list(self, devices: list[Devices] | None = None):
        if devices is None:
            return [];
        return Devices().toListDict(devices, None)
    
    def list_to_ages(self, ages: list[Ages] | None = None):
        if ages is None:
            return [];
        return Ages().fromListDict(ages, Ages)
    def list_to_genders(self, genders: list[Genders] | None = None):
        if genders is None:
            return [];
        return Genders().fromListDict(genders, Genders)
    def list_to_devices(self, devices: list[Devices] | None = None):
        if devices is None:
            return [];
        return Devices().fromListDict(devices, Devices)

    def is_published(self):
        return self.ad_group_id is not None and self.ad_group_id > 0
    def to_dict(self, fields=None):
        campaign_id = self.campaign_id
        ad_group_id = self.ad_group_id
        if campaign_id == 0:
            campaign_id = None;
        if ad_group_id == 0:
            ad_group_id = None;
        
        return DictUtils.remove_none_values({
            "id": self.id,
            "campaign_id": campaign_id,
            "name": self.name,
            "status": self.status,
            "ages": Ages().toListDict(self.ages, None),
            "genders": Genders().toListDict(self.genders, None),
            "devicesTargeted": Devices().toListDict(self.devicesTargeted, None),
            "devicesExcluded": Devices().toListDict(self.devicesExcluded, None),
            "is_removed": self.is_removed,
            "bid": self.bid,
            "strategie": self.strategie,
            "ad_group_id": ad_group_id,
            "owner": self.owner,
            "provider": self.provider,
            "clientCustomerId": self.clientCustomerId,
            "accountId": self.accountId,
            "campaign_id_parent": self.campaign_id_parent,
            "createdAt": DateUtils.convert_firestore_timestamp_to_str(self.createdAt),
            "createdBy": self.createdBy,
            "api_version": self.api_version,
            "google_ads_ad_group": self.google_ads_ad_group
        })
        