import { LabelComponent, Node, SpriteComponent, SpriteFrame } from "cc";
// 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

import { LiangLiangSDK } from "./liangliangSDK";

const {ccclass, property} = cc._decorator;

interface JumpData
{
    icon:string,
    app_id : string,
    game_id : string,
    big_icon: string,
    app_path: string,
    skipIcon: boolean;
    name:string;
}

var wx = window["wx"];

@ccclass
export default class JumpIcon extends cc.Component 
{

    static _allspriteFrame :{[key:string]:SpriteFrame} = {};

    @property({
        type:SpriteComponent
    })
    sprite:SpriteComponent=null;

    @property({
        type:LabelComponent
    })
    nameLabel:LabelComponent = null;

    _data: JumpData; 

    Init(data:JumpData)
    {
        this._data = data;
        if(!this._data.skipIcon)
        {
            var iconname = data.icon;
            if(this.sprite.node.width > 196 )
            {
                iconname = data.big_icon;
            }

            if(JumpIcon._allspriteFrame[iconname])   
            {
                this.sprite.spriteFrame = JumpIcon._allspriteFrame[iconname];
            }
            else
            {
                let self = this;
                cc.loader.load(iconname, (err, texture) =>
                {                   
                    if (texture && !err)
                    {
                        var spriteFrame = new cc.SpriteFrame(texture);
                        JumpIcon._allspriteFrame[iconname] = spriteFrame;
                        self.sprite.spriteFrame = spriteFrame;
                    }
                });
            }
        }     
        this.nameLabel.string = this._data.name;
    }

    start ()
    {

    }

    update (dt) 
    {

    }

    onEnable()
    {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStartCallback, this, true);
    }

    onDisable()
    {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStartCallback, this, true);
    }

    onTouchStartCallback()
    {
        let self = this;
        if(window[wx]!=null)
        {
            wx.navigateToMiniProgram({
                appId: this._data.app_id,
                path: this._data.app_path,
                success: (res) => 
                {
                    LiangLiangSDK.CpaReport(self._data);
                },
                fail: (res) => {},
                complete: (res) => {},
            });
        }
        else
        {
            console.log("点中了图标 : " + this._data.name);
        }
    }
}
