import { _decorator, Component, Node, math, Sprite} from 'cc';
import { Card } from './Card';
const { ccclass, property } = _decorator;

export const RAD_180 = 3.14159;

@ccclass('CardRotator')
export class CardRotator extends Component 
{
    public m_RotMaxTime: number = 0.5;
    public m_CanRotate: boolean = false;
    public m_RotSpeed: number = 1.5;
    
    private m_DisplayCard: boolean = false;
    private m_RotTimer: number = 0;
    private m_XScale: number = 0;

    @property({type: Sprite})
    iconSprite: Sprite;

    @property({type: Node})
    front: Node;

    @property({type: Node})
    back: Node;
    
    @property({type: Node})
    public card: Card;

    start()
    {
        this.m_XScale = this.node.getScale().x;
    }

    update(deltaTime: number) 
    {
        if (this.m_CanRotate)
        {
            if (this.m_RotTimer < this.m_RotMaxTime)
            {
                this.m_RotTimer += deltaTime * this.m_RotSpeed;
                let t = this.m_RotTimer / this.m_RotMaxTime;
                
                if (t >= 0.5)
                    this.fn_displayCard(this.m_DisplayCard);

                let scale = math.lerp(this.m_XScale, -this.m_XScale, t);
                this.node.setScale(scale, this.node.getScale().y);
            }
            else 
            {
                this.node.setScale(Math.round(this.node.getScale().x), this.node.getScale().y);

                this.m_CanRotate = false;
                this.m_RotTimer = 0;
                this.m_XScale = this.node.getScale().x;
            }
        }
    }

    public fn_TriggerRotation(displayCard: boolean) 
    {
        this.m_CanRotate = true;
        this.m_DisplayCard = displayCard;
    }

    public fn_displayCard(showCard: boolean) 
    {
        this.iconSprite.enabled = showCard;
        this.front.active = showCard;
        this.back.active = !showCard;
    }
}

