from dataclasses import dataclass
from typing import Optional, List

from dacite import from_dict

from pokemontcgsdkasync import SingleQuery, MultipleQuery
from pokemontcgsdkasync.ability import Ability
from pokemontcgsdkasync.ancienttrait import AncientTrait
from pokemontcgsdkasync.attack import Attack
from pokemontcgsdkasync.cardimage import CardImage
from pokemontcgsdkasync.cardmarket import Cardmarket
from pokemontcgsdkasync.legality import Legality
from pokemontcgsdkasync.querybuilder import QueryBuilder
from pokemontcgsdkasync.resistance import Resistance
from pokemontcgsdkasync.set import Set
from pokemontcgsdkasync.tcgplayer import TCGPlayer
from pokemontcgsdkasync.weakness import Weakness


@dataclass
class Card:
    RESOURCE = 'cards'

    abilities: Optional[List[Ability]]
    artist: Optional[str]
    ancientTrait: Optional[AncientTrait]
    attacks: Optional[List[Attack]]
    cardmarket: Optional[Cardmarket]
    convertedRetreatCost: Optional[int]
    evolvesFrom: Optional[str]
    flavorText: Optional[str]
    hp: Optional[str]
    id: str
    images: CardImage
    legalities: Legality
    regulationMark: Optional[str]
    name: str
    nationalPokedexNumbers: Optional[List[int]]
    number: str
    rarity: Optional[str]
    regulationMark: Optional[str]
    resistances: Optional[List[Resistance]]
    retreatCost: Optional[List[str]]
    rules: Optional[List[str]]
    set: Set
    subtypes: Optional[List[str]]
    supertype: str
    tcgplayer: Optional[TCGPlayer]
    types: Optional[List[str]]
    weaknesses: Optional[List[Weakness]]

    @staticmethod
    def find(card_id: str) -> SingleQuery:
        return QueryBuilder(Card, Card.transform).find(card_id)

    @staticmethod
    def where(**kwargs) -> MultipleQuery:
        return QueryBuilder(Card, Card.transform).where(**kwargs)

    @staticmethod
    def all() -> MultipleQuery:
        return QueryBuilder(Card, Card.transform).all()

    @staticmethod
    def transform(response):

        # Transform json keys into names that are safe for python properties
        if response.get('tcgplayer', {}).get('prices', {}).get('1stEditionNormal'):
            response['tcgplayer']['prices']['firstEditionNormal'] = response['tcgplayer']['prices'].pop(
                '1stEditionNormal')
        if response.get('tcgplayer', {}).get('prices', {}).get('1stEditionHolofoil'):
            response['tcgplayer']['prices']['firstEditionHolofoil'] = response['tcgplayer']['prices'].pop(
                '1stEditionHolofoil')

        response = from_dict(Card, response)

        return response
