import { _decorator, ccenum, Component, Node, Color, Sprite, Animation, AnimationClip, SpriteFrame, UITransform } from 'cc';
import { CardRotator } from './CardRotator';
import { CardManager } from '../../../Managers/in-game/board/CardManager';
import { CardTypes } from '../../../Managers/data/DataModel';
import { Cards_Constants } from '../../../constants/Cards_Constants'

const { ccclass, property } = _decorator;

@ccclass('Card')
export class Card extends Component 
{
    @property({type: Sprite})
    public m_IconSprite: Sprite;

    @property({type: UITransform})
    public m_CardBackUITransform: UITransform;

    @property({type: Number})
    public m_CardFlipInterval: number;

    @property({type: Animation})
    public m_Animation: Animation;

    @property({type: AnimationClip})
    public m_CardScaleClip: AnimationClip;

    @property({type: Node})
    public m_ParticleSystemNode: Node;

    public m_CardRotator: CardRotator | null = null;
    private m_CardManager: CardManager = null;

    public m_PosX: number;
    public m_PosY: number;

    public m_CardType: CardTypes;
    public m_ImageAsset: SpriteFrame;

    public x: number = 0;
    public y: number = 0;

    public fn_InitCoords(i: number, j: number) 
    {
        this.x = i;
        this.y = j;
    }

    fn_Init(cardType: CardTypes, spriteFrame: SpriteFrame, cardManager: CardManager)
    {
        this.m_CardType = cardType;
        this.m_ImageAsset = spriteFrame;

        this.m_IconSprite.spriteFrame = spriteFrame; 

        // getcomp for cardrot
        let cardRotator = this.node.getComponent(CardRotator);
        cardRotator.fn_displayCard(false); // by default all cards should be hidden
        this.m_CardManager = cardManager;
    }

    start() 
    {
        this.m_ParticleSystemNode.active = false;
        
        if (!this.m_CardRotator)
            this.m_CardRotator = this.getComponent(CardRotator);

        this.m_PosX = this.node.getPosition().x;
        this.m_PosY = this.node.getPosition().y;
    }

    fn_flipCardOnSelection() 
    {
        if (this.m_CardRotator.front.active || !this.m_CardManager.CanFlip)
            return;

        this.m_CardManager.fn_InitSelectedCard(this);
    }

    public fn_flipCard()
    {
        if (!this.m_CardRotator)
            this.m_CardRotator = this.getComponent(CardRotator);

        this.fn_DisplayCard();
        setTimeout(() => {
            this.fn_HideCard();
        }, Cards_Constants.MILLI_SEC * this.m_CardFlipInterval);
    }

    public fn_DisplayCard()
    {
        this.m_CardRotator.fn_TriggerRotation(true);
    }

    public fn_HideCard()
    {
        this.m_CardRotator.fn_TriggerRotation(false);
    }

    public fn_OnMatchFound()
    {
        this.m_Animation.play(this.m_CardScaleClip.name);
        this.m_ParticleSystemNode.active = true;
    }
    
    public fn_DisableSprite()
    {
        this.m_IconSprite.enabled = false;
    }
}

