
import { game, IGameConfig, ISceneInfo, director, view, loader } from 'cc';

class Prepare {
    protected config: IGameConfig & { adapter?: any } = {};

    initConfig() {

    }

    findCanvas(name: string) {
        var canvas = <HTMLCanvasElement>document.getElementById(name);
        if (!canvas || canvas.tagName !== 'CANVAS') {
            console.error("Cannot find canvas(#GameCanvas)");
        }
        var width = canvas.width;
        var height = canvas.height;
        var container = document.createElement('div');
        if (canvas && canvas.parentNode) {
            canvas.parentNode.insertBefore(container, canvas);
        }
        container.setAttribute('id', 'Cocos3dGameContainer');
        container.appendChild(canvas);
        var frame = (container.parentNode === document.body) ? document.documentElement : container.parentNode;
        this.addClass(canvas, name);
        canvas.setAttribute('width', `${width}` || '480');
        canvas.setAttribute('height', `${height}` || '320');
        canvas.setAttribute('tabindex', '99');
        return { frame, canvas, container };
    };

    addClass(element: HTMLElement, name: string) {
        var hasClass = (' ' + element.className + ' ').indexOf(' ' + name + ' ') > -1;
        if (!hasClass) {
            if (element.className) {
                element.className += ' ';
            }
            element.className += name;
        }
    };

    protected onStart() {
        director.loadScene('db://assets/Test.scene', null,() => {
            view.setDesignResolutionSize(960, 640, 4);
            loader.onProgress = null;
        })
    }

    start(scene: ISceneInfo[], debug: boolean) {

        this.config.assetOptions = {
            libraryPath: 'res/import',
            rawAssetsBase: 'res/raw-',
            rawAssets: {},
        }

        this.config.scenes = scene;
        this.config.showFPS = !!debug;
        this.config.debugMode = debug ? 1 : 3;
        this.config.adapter = this.findCanvas('GameCanvas');
        this.config.frameRate = 60;
        this.config.customJointTextureLayouts = [];
        game.init(this.config);
        game.run(this.onStart);
    }
}

(new Prepare).start([{"url":"db://assets/Test.scene","uuid":"e3e91040-9e1c-4b10-98ac-df65e284e15d"}], true);