// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class CoverClass extends cc.Component {

    // @property
    // url: string = '';
    // @property(cc.Node)
    // coverFrame: cc.SpriteFrame = null;
    coverNode: cc.Node = null;
    loaded = false;
    spriteFrameCache = {};

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.coverNode = this.node.getChildByName('cover')
    }

    start () {
        
        // this.coverFrame = this.coverNode.getComponent(cc.Sprite).spriteFrame
    }
    setSpriteFrame(spriteFrame) {
        if(!this.coverNode) {
            return;
        }
        if(!spriteFrame) {
            return;
        }
        const {width, height} = spriteFrame.getOriginalSize()
        this.coverNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
        this.coverNode.width = width;
        this.coverNode.height = height;
        const sx = this.node.width / width;
        const sy = this.node.height / height;
        const s = Math.min(sx, sy);
        const scale = Math.round(s * 1000) / 1000;
        this.coverNode.scale = scale * .9
        return spriteFrame
    }
    setUrl(url) {
        if (!url) {
            return;
        }
        if (this.spriteFrameCache[url]) {
            this.setSpriteFrame(this.spriteFrameCache[url]);
            return;
        }
        if (this.coverNode) {
            cc.assetManager.loadRemote( url, (err, tex) => {
                const spriteFrame = new cc.SpriteFrame(tex);
                // console.log(spriteFrame);
                this.setSpriteFrame(spriteFrame);
                this.spriteFrameCache[url] = spriteFrame
            });
        }
       
       
    }

    // update (dt) {}
}
