import { buttonOnClick, onHomeworkFinish, getSpriteFrimeByUrl } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {


    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
    }

    addPreloadAnima() {

    }

    showLoading() {
        cc.find(`Canvas/loading`).active = true;
    }
    hideLoading() {
        cc.find(`Canvas/loading`).active = false;
    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
    }

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
    }

    initView() {
        this.initBg();

        window["cameraHandler"].takePictureCallback = (err, url) => {
            if (err) {
                console.log(err);
                this.hideLoading();
                return;
            }
            const pic = cc.find(`Canvas/border/pic_bg/picture`);
            getSpriteFrimeByUrl(url, (frame) => {
                pic.getComponent(cc.Sprite).spriteFrame = frame;
                pic.active = true;
                this.hideLoading();
            });
        }
    }

    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
    }

    initListener() {
        const btn = cc.find(`Canvas/border/upload`);
        buttonOnClick(btn, () => {
            this.showLoading();
            window["cameraHandler"].openCamera();
        });
    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }

}
