import {DelayTask} from '../common/DelayPromise';
import ResouceLoadError from '../common/ErrorDefine';

let SafeLoader = (
  function()
  {

    let _load=function(resources)
    {
        return new Promise(function(resolve,reject){
            cc.loader.load(resources, (error, res) => {
                if (error) {
                    reject(new ResouceLoadError(error,res));
                } else {
                    resolve(res);
                }
            });
        });
    };

    let safeLoad = function (resources, callback, curTimes,maxTime,timeout) {
        Promise.race([_load,DelayTask(timeout || 1000)])
        .then(function(res)
        {
            callback && callback(null,res);
        })
        .catch(function(err){
            if(curTimes + 1 > (maxTime || 2))
            {
                callback && callback(err.getError(),err.getRes());
            }
            else
            {
                safeLoad(resources, callback, curTimes + 1,maxTime);
            }
        }
        );
    };


    return {
      safeLoad:safeLoad,
    };
  }
)();

export default SafeLoader;