import { defaultData } from "../script/defaultData";

export class MyCocosSceneComponent extends cc.Component {

  // 生命周期 onLoad
  onLoad() {
    this.initSceneData();
    this.initSize();
  }

  _imageResList = null;
  _audioResList = null;
  _animaResList = null;
  initSceneData() {
    this._imageResList = [];
    this._audioResList = [];
    this._animaResList = [];
  }

  _designSize = null;  // 设计分辨率
  _frameSize = null;  // 屏幕分辨率
  _mapScaleMin = null;  // 场景中常用缩放（取大值）
  _mapScaleMax = null;  // 场景中常用缩放（取小值）
  _cocosScale = null;  // cocos 自缩放 （较少用到）
  initSize() {
    // 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
    let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
    let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
    let f = screen_size >= design_size
    cc.Canvas.instance.fitHeight = f
    cc.Canvas.instance.fitWidth = !f

    const frameSize = cc.view.getFrameSize();
    this._frameSize = frameSize;

    this._designSize = cc.view.getDesignResolutionSize();

    let sx = cc.winSize.width / frameSize.width;
    let sy = cc.winSize.height / frameSize.height;
    this._cocosScale = Math.min(sx, sy);

    sx = frameSize.width / this._designSize.width;
    sy = frameSize.height / this._designSize.height;
    this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;//其他
    this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;//背景

    cc.director['_scene'].width = frameSize.width;
    cc.director['_scene'].height = frameSize.height;
  }

  data = null;

  // 生命周期 start
  start() {
    if (window && (<any>window).courseware && (<any>window).courseware.getData) {
      (<any>window).courseware.getData((data) => {
        this.log('data server:' + data);
        this.data = data || this.getDefaultData();
        this.data = JSON.parse(JSON.stringify(this.data));
        this.preloadItem();
      })
    } else {
      this.data = this.getDefaultData();
      this.data = JSON.parse(JSON.stringify(this.data));
      this.preloadItem();
    }
  }

  getDefaultData() {
    return defaultData;
  }

  preloadItem() {
    this.addPreloadImage();
    this.addPreloadAudio();
    this.addPreloadAnima();
    this.preload();
  }

  addPreloadImage() {
  }

  addPreloadAudio() {
  }

  addPreloadAnima() {
  }

  preload() {
    const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
    cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

      if (window && window["air"]) {
        // window["air"].onCourseInScreen = (next) => {
        //   window["air"].isCourseInScreen = true;
        //   this.onLoadEnd();
        //   next();
        // };
        this.onLoadEnd();
        window["air"].hideAirClassLoading();
      } else {
        this.onLoadEnd();
      }

      cc.debug.setDisplayStats(false);
    });
  }

  log (str) {
    const node = cc.find('middleLayer');
    if(node){
      node.getComponent('middleLayer').log(str);
    }else{
      cc.log(str);
    }
  }

  onLoadEnd() {

  }









  
  // ------------------------------------------------
  getSprNode(resName) {
    const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
    const node = new cc.Node();
    node.addComponent(cc.Sprite).spriteFrame = sf;
    return node;
  }


  getSpriteFrimeByUrl(url, cb) {
    cc.loader.load({ url }, (err, img) => {
      const spriteFrame = new cc.SpriteFrame(img)
      if (cb) {
        cb(spriteFrame);
      }
    })
  }

  getSprNodeByUrl(url, cb) {
    const node = new cc.Node();
    const spr = node.addComponent(cc.Sprite);
    this.getSpriteFrimeByUrl(url, (sf) => {
      spr.spriteFrame = sf;
      if (cb) {
        cb(node);
      }
    })
  }

  playAudioByUrl(audio_url, cb = null) {
    if (audio_url) {
      cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
        const audioId = cc.audioEngine.play(audioClip, false, 0.8);
        if (cb) {
          cc.audioEngine.setFinishCallback(audioId, () => {
            cb();
          });
        }
      });
    }else{
      cb && cb();
    }
  }

  getRomoteDragon(parent:cc.Node){
    // let bone = {
    //   bone_ske: "https://wxmini-resource.hortorgames.com/images/20180919/20180919164706/box_anim_ske.json",
    //   bone_tex :"https://wxmini-resource.hortorgames.com/images/20180919/20180919164709/box_anim_tex.json",
    //   bone_tex_img:"https://wxmini-resource.hortorgames.com/images/20180919/20180919164704/box_anim_tex.png"
    //   };

    let bone = this.data.questions[0].dragonBoneData;

    // cc.loader.load([bone.skeJsonData.url, bone.texJsonData.url, bone.texPngData.url], function(err, results) {
    //     let node = new cc.Node();
    //     let dragonBonesNode = node.addComponent(dragonBones.ArmatureDisplay);
    //     let _dragonAsset = new dragonBones.DragonBonesAsset();
    //     _dragonAsset.dragonBonesJson = JSON.stringify(results.getContent(bone.skeJsonData.url));
    //     let _dragonAtlasAsset = new dragonBones.DragonBonesAtlasAsset();
    //     _dragonAtlasAsset.atlasJson = JSON.stringify(results.getContent(bone.texJsonData.url));
    //     _dragonAtlasAsset.texture = results.getContent(bone.texPngData.url);

    //     dragonBonesNode.dragonAsset = _dragonAsset;
    //     dragonBonesNode.dragonAtlasAsset = _dragonAtlasAsset;
    //     dragonBonesNode.buildArmature('right',node);
    //     dragonBonesNode.playAnimation('right',0);
    //     parent.addChild(node);
    // }.bind(this));

    
    cc.assetManager.loadRemote(bone.texPngData.url, (error, texture) => {
        cc.assetManager.loadRemote(bone.texJsonData.url, (error, atlasJson) => {
            cc.assetManager.loadRemote(bone.skeJsonData.url, (error, dragonBonesJson) => {

                let node = new cc.Node();
                let dragonBonesNode = parent.addComponent(dragonBones.ArmatureDisplay);
                var atlas = new dragonBones.DragonBonesAtlasAsset();
                atlas.atlasJson = JSON.stringify(atlasJson);
                atlas.texture = texture;

                var asset = new dragonBones.DragonBonesAsset();
                asset.dragonBonesJson = JSON.stringify(dragonBonesJson);

                dragonBonesNode.dragonAtlasAsset = atlas;
                dragonBonesNode.dragonAsset = asset;

                // console.log(atlas);
                // console.log(asset);
                // console.log(dragonBonesNode);

                // dragonBonesNode.armatureName = 'newAnimation';

                
                // let armatureNames = dragonBonesJson.armature.map(data => data.name);
                // if (armatureNames.length > 0) {
                //     // dragonBonesNode.armatureName = ;
                //     // dragonBonesNode.playAnimation('newAnimation',0);

                //     dragonBonesNode.buildArmature(armatureNames[0],node);
                //     dragonBonesNode.playAnimation('newAnimation',0);
                // }

                dragonBonesNode.buildArmature("armature",node);
                dragonBonesNode.playAnimation('newAnimation',0);
                parent.addChild(node);



                // // var atlas = new dragonBones.DragonBonesAtlasAsset();
                // var atlas = dragonBonesNode.dragonAtlasAsset;
                // atlas.atlasJson = JSON.stringify(atlasJson);
                // atlas.texture = texture;

                // // var asset = new dragonBones.DragonBonesAsset();
                // var asset = dragonBonesNode.dragonAsset;
                // asset.dragonBonesJson = JSON.stringify(dragonBonesJson);

                // // dragonBonesNode.dragonAtlasAsset = atlas;
                // // dragonBonesNode.dragonAsset = asset;

                // // console.log(atlas);
                // // console.log(asset);
                // // console.log(dragonBonesNode);

                // // dragonBonesNode.armatureName = 'newAnimation';
                // dragonBonesNode.buildArmature('newAnimation',parent);
                // dragonBonesNode.playAnimation('newAnimation',0);
                // // parent.addChild(node);
            });
        });
    });


  }


  getLoaclDragon(parent:cc.Node,name:string){
    let bone = {
      bone_ske: "assets/NEXT_test001/dragonBones/" + name + "/" + name + "_ske.json",
      bone_tex :"assets/NEXT_test001/dragonBones/" + name + "/" + name + "_tex.json",
      bone_tex_img:"assets/NEXT_test001/dragonBones/" + name + "/" + name + "_tex.png"
      };


    // let bone = this.data.questions[0].dragonBoneData;
    // self.crossNode.removeAllChildren();
    cc.resources.load([bone.bone_ske, bone.bone_tex, bone.bone_tex_img], function(err, results) {
        let node = new cc.Node();
        let dragonBonesNode = node.addComponent(dragonBones.ArmatureDisplay);
        let _dragonAsset = new dragonBones.DragonBonesAsset();
        _dragonAsset.dragonBonesJson = JSON.stringify(results.getContent(bone.bone_ske));
        let _dragonAtlasAsset = new dragonBones.DragonBonesAtlasAsset();
        _dragonAtlasAsset.atlasJson = JSON.stringify(results.getContent(bone.bone_tex));
        _dragonAtlasAsset.texture = results.getContent(bone.bone_tex_img);

        dragonBonesNode.dragonAsset = _dragonAsset;
        dragonBonesNode.dragonAtlasAsset = _dragonAtlasAsset;
        dragonBonesNode.buildArmature(name,node);
        dragonBonesNode.playAnimation(name,0);
        parent.addChild(node);
    }.bind(this));
  }

}


