import Common from './Common'
import LogicUnitManager from '../framework/LogicUnitManager';
import Event from '../net/Event';
import Define from './Define'

export default class PreloadManager 
{
    constructor()
    {
        if( PreloadManager.unique !== undefined ){
            return PreloadManager.unique; 
        }

        this.init();

        PreloadManager.unique = this

    }

    init()
    {
        this.loadPrefabDone = false;
        this._PrefabMap = {};
        this.loadAnimDone = false;
        this._AnimMap = {};
        this.loadAtlasDone = false;
        this._AtlasMap = {};
        this._lum = LogicUnitManager;

    }

    run()
    {
        this.preloadPrefab();
        this.preloadAnim();
        this.preloadAtlas();
    }

    preloadAtlas()
    {
        var self = this;
        var atlasUrl = [
            'plists/hall', 
            'plists/start',
            'plists/reg',];
        cc.loader.loadResArray(atlasUrl, cc.SpriteAtlas, function(err, atlas){
            self.loadAtlasDone = true;
            for (var i = 0; i < atlas.length; ++i)
            {
                self._AtlasMap[atlasUrl[i]] = atlas[i];
                console.log(atlasUrl[i]);
                console.log(atlas[i]);
            }
            self._lum.getBehavior('LoginBehavior').emit(Event.COM_MSG.PRELOAD_DONE);
        })
    }

    getAtlasByUrl(url)
    {
        url = Define.Prefix + url
        return this._AtlasMap[url];
    }

    preloadPrefab()
    {
        var self = this;
        var prefabUrl = Define.Prefix +'prefab';
        cc.loader.loadResDir(prefabUrl, function(err, objects, urls){
            console.log("load prefab done");
            for (var i = 0; i < objects.length; ++i)
            {
                self._PrefabMap[urls[i]] = objects[i];
                console.log(urls[i]);
            }
            self.loadPrefabDone = true;
            self._lum.getBehavior('LoginBehavior').emit(Event.COM_MSG.PRELOAD_DONE);
        })
    }

    getPrefabByUrl(url)
    {
        url = Define.Prefix +url
        return this._PrefabMap[url];
    }

    preloadAnim()
    {
        var self = this;
        var animUrl = Define.Prefix + 'anim';
        cc.loader.loadResDir(animUrl, function(err, objects, urls){
            console.log("load anim done");
            for (var i = 0; i < objects.length; ++i)
            {
                self._AnimMap[urls[i]] = objects[i];
                console.log(urls[i]);
            }
            self.loadAnimDone = true;
            self._lum.getBehavior('LoginBehavior').emit(Event.COM_MSG.PRELOAD_DONE);
        })
    }

    getAnimByUrl(url)
    {
        url = Define.Prefix +url
        return this._AnimMap[url];
    }
}
