from dataclasses import dataclass
from datetime import datetime
from typing import Any

from adafri.utils import DateUtils
from google.cloud.firestore_v1.transforms import Sentinel

from ......utils import DictUtils, get_request_fields, init_class_kwargs
from .....base.firebase_collection import FirebaseCollectionBase
from .base_ad_fields import BASE_AD_PICKABLE_FIELDS, STANDARD_FIELDS, BaseAdFieldsProps


def filter_request_fields(fields, default_fields = BASE_AD_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 BaseAd(FirebaseCollectionBase):
    id: str
    ad_id: int
    ad_group_id: int
    adgroup_id_parent: str
    name: str
    status: str
    is_removed: bool = False
    owner: str
    clientCustomerId: str
    accountId: str
    createdAt: any
    createdBy: str
    class_object = None
    api_version: str = "v0"
    __baseFields: BaseAdFieldsProps

    def __init__(self, ad=None, collection_name=None, **kwargs):
        _ad = ad
        if type(ad) is str:
            _ad = {"id": ad}
        # if ad is not None:
        #     print('init first', ad['id'])
        (cls_object, keys, data_args) = init_class_kwargs(self, _ad, STANDARD_FIELDS, BaseAdFieldsProps, collection_name, ['id'], **kwargs)
        super().__init__(**data_args);
        for key in keys:
            if 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]) 
        self.class_object = BaseAd

    def is_published(self):
        return self.ad_id is not None and self.ad_id > 0


    @staticmethod
    def generate_model(_key_="default_value"):
        ad = {};
        props = BaseAdFieldsProps
        for k in DictUtils.get_keys(props):
            ad[k] = props[k][_key_];
        return ad;

    
    def to_dict(self, fields=None):
        ad_id = self.ad_id
        ad_group_id = self.ad_group_id
        if ad_id == 0:
            ad_id = None;
        if ad_group_id == 0:
            ad_group_id = None;
        
        return DictUtils.remove_none_values({
            "id": self.id,
            "ad_id": ad_id,
            "name": self.name,
            "status": self.status,
            "is_removed": self.is_removed,
            "ad_group_id": ad_group_id,
            "owner": self.owner,
            "clientCustomerId": self.clientCustomerId,
            "accountId": self.accountId,
            "adgroup_id_parent": self.adgroup_id_parent,
            "createdAt": DateUtils.convert_firestore_timestamp_to_str(self.createdAt),
            "createdBy": self.createdBy,
            "api_version": self.api_version
        })
        