import { setText } from 'assets/scripts/entityUtils';
import { setScale } from 'assets/scripts/transformUtils';
import ScillaComponent from 'components/base/ScillaComponent';
import { TextureRenderer } from 'scilla-components/src';
import { createTexture, EngineConfig, Entity, Texture } from 'scilla/src';

export default class RankItem extends ScillaComponent {
    score: Entity;
    rank: Entity;
    name: Entity;
    avatar: Entity;
    onAwake() {
        super.onAwake();
    }

    async setdata(data) {
        // console.log(data);
        setText(this.score, data.score + '');
        setText(this.rank, data.rank);
        setText(this.name, data.nickName);

        const texRender = this.avatar.getComponent(TextureRenderer);
        const texture = await this.loadTexture(data.avatar);
        texRender.texture = texture;
        setScale(this.avatar, 40 / texture.bounds.width)
    }

    onUpdate(t) {
        super.onUpdate(t);

    }

    private loadImage = (url: string): Promise<HTMLImageElement> => {
        return new Promise<HTMLImageElement>((resolve, reject) => {
            let img = new Image();
            if (EngineConfig.imgCrossOrigin) {
                img.setAttribute('crossOrigin', 'anonymous');
            }
            img.onload = function (e) {
                resolve(img);
            };
            img.onerror = function (e) {
                reject(e);
            };
            img.src = url;
        });
    }

    private loadTexture = async (url: string): Promise<Texture> => {
        const img = await this.loadImage(url);
        const texture = createTexture(img);
        return texture;
    }
}
