import {
  MySprite,
  getMinScale,
  ShapeRect,
  tweenChange,
  randomSortByArr,
  Label,
  showPopParticle,
  moveItem,
  removeItemFromArr,
  rotateItem,
  ShapeRectNew
} from "./Unit";

import { CartoonAnimation } from './CartoonAnimation'

export class Cartoon {
  
  // 系统缩放比例
  mapScale = 1;
  stageWidth;
  stageHeight;
  clientWidth;
  clientHeight;
  // 音乐 和 图片的缓冲区
  audio = new Map();
  images = new Map();
  imagesOriginSize = new Map();
  
  // 坐标原点 包含缩放
  originX = 0;
  originY = 0;
  
  setOrigin = (x, y)=>{
    this.originX = x;
    this.originY = y;
  }
  getOrigin = ()=>{
    return {
      x: this.originX,
      y: this.originY
    }
  }
  
  // 相对坐标原点 包含缩放 用于添加孩子动画元素
  relativeOriginX = 0;
  relativeOriginY = 0;
  setRelativeOrigin = (x, y)=>{
    this.relativeOriginX = x;
    this.relativeOriginY = y;
  }
  getRelativeOrigin = ()=>{
    return {
      x: this.relativeOriginX,
      y: this.relativeOriginY
    }
  }
  
  // 存放音乐和图片的地址
  audioObj = {}
  imageObj = {}
  _currentPlayAudio;
  // 添加音乐
  addAudio = ( key, url ) => {
    this.audioObj[key] = url
  };
  // 添加音乐
  addImage = ( key, url ) => {
    this.imageObj[key] = url
  };
  // 播放音乐
  _playingNow = []
  playAudio = function( key, now = false, callback = null) {
    const audio = this.audio.get(key);
    if (audio) {
      if (now) {
        audio.pause();
        audio.currentTime = 0;
      }
      if (callback) {
        audio.onended = () => {
          let index = this._playingNow.indexOf(audio)
          if(index != -1){
            this._playingNow.splice(index,1)
          }
          callback();
        };
      }
      audio.play();
      audio.callback = callback
      this._playingNow.push(audio)   
      this._currentPlayAudio = audio;
    }
  }
  stopAllAudio(){
    this._playingNow.forEach(audio=>{
      try{
        audio.onended && audio.onended()
        audio.pause();
        audio.currentTime = 0;
      }catch(err){
        console.log(err)
      }
    })
    this._playingNow = []
  }
  stopAudio(){
    if(this._currentPlayAudio){
      this._currentPlayAudio.pause();
      this._currentPlayAudio.currentTime = 0;
    }
  }
  // 异步加载图片 音频资源
  loadResources = ()=> {
    const pr = [];
    for(let key in this.imageObj){
      const p = this.preloadImage(this.imageObj[key]).then( (img:any) => {
        this.images.set(key, img);
        this.imagesOriginSize.set(key, {width:img.width, height:img.height});
      }).catch(err => console.log(key));
      pr.push(p);
    };
    for(let key in this.audioObj){
      const a = this.preloadAudio(this.audioObj[key]).then( (audio:any) => {
        this.audio.set(key, audio);
      }).catch(err => console.log(key));
      pr.push(a);
    };
    return Promise.all(pr);
  }
  
  // 预加载图片
  preloadImage = (url) => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.src = url;
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }
  // 预加载音频
  preloadAudio = (url) => {
    return new Promise((resolve, reject) => {
      const audio = new Audio();
      audio.oncanplay = a => {
        resolve(audio);
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
    });
  }
  
  // 缓存页面元素
  cartoonElementsBuffer = {}
  createCartoonElement = (key, type, width?:number, heigth?:number, initX?:number, initY?:number)=>{
    this.cartoonElementsBuffer[key] = {}
    this.cartoonElementsBuffer[key].id = key;
    this.cartoonElementsBuffer[key].width = width;
    this.cartoonElementsBuffer[key].heigth = heigth;
    this.cartoonElementsBuffer[key].width = width;
    this.cartoonElementsBuffer[key].heigth = heigth;
    
    this.cartoonElementsBuffer[key].x = initX;
    this.cartoonElementsBuffer[key].y = initY;
    switch(type){
      case "MySprite": this.cartoonElementsBuffer[key].ref = new MySprite(); break;
      case "ShapeRect": this.cartoonElementsBuffer[key].ref = new ShapeRect(); break;
      case "ShapeRectNew": this.cartoonElementsBuffer[key].ref = new ShapeRectNew(); break;
      case "Label": this.cartoonElementsBuffer[key].ref = new Label(); break;
      default : this.cartoonElementsBuffer[key].ref = new MySprite(); break;
    }
    this.cartoonElementsBuffer[key].ref.x = initX;
    this.cartoonElementsBuffer[key].ref.y = initY;
    this.cartoonElementsBuffer[key].animation = new CartoonAnimation(this.cartoonElementsBuffer[key].ref)
    return this.cartoonElementsBuffer[key]
  }

  createElement = (type, initX?:number, initY?:number)=>{
    let element;
    switch(type){
      case "MySprite": element = new MySprite(); break;
      case "ShapeRect": element = new ShapeRect(); break;
      default : element = new MySprite(); break;
    }
    element.x = initX;
    element.y = initY;
    return element
  }

  createLabel = ({
    text,
    fontName,
    fontColor,
    fontSize,
    textAlign
  }, initX?, initY?)=>{
    let element = new Label()
    element.text = text;
    element.fontName = fontName;
    element.fontColor = fontColor;
    element.fontSize = fontSize;
    element.textAlign = textAlign;
    element.x = initX;
    element.y = initY;
    return element
  }

  getCartoonElementRef = (key)=>{
    if(this.cartoonElementsBuffer[key]){
      return this.cartoonElementsBuffer[key].ref;
    }else{
      return undefined
    }
  }
  getCartoonElement = (key)=>{
    return this.cartoonElementsBuffer[key]
  }
  setCartoonElementPosition = (key, posi)=>{
    this.cartoonElementsBuffer[key].ref.x = posi.x
    this.cartoonElementsBuffer[key].ref.y = posi.y
    this.cartoonElementsBuffer[key].x = posi.x
    this.cartoonElementsBuffer[key].y = posi.y
  }
  setCartoonElementPositionX = (key, x)=>{
    this.cartoonElementsBuffer[key].ref.x = x
    this.cartoonElementsBuffer[key].x = x
  }
  setCartoonElementRelativePositionX = (key, x)=>{
    this.cartoonElementsBuffer[key].relativeX = x
  }
  setCartoonElementPositionY = (key, y)=>{
    this.cartoonElementsBuffer[key].ref.y = y
    this.cartoonElementsBuffer[key].y = y
  }
  setCartoonElementRelativePositionY = (key, y)=>{
    this.cartoonElementsBuffer[key].relativeY = y
  }
  getCartoonElementPosition = (key)=>{
    return {
      x: this.cartoonElementsBuffer[key].x,
      y: this.cartoonElementsBuffer[key].y
    }
  }
  getCartoonElementRelativePosition = (key)=>{
    return {
      x: this.cartoonElementsBuffer[key].relativeX,
      y: this.cartoonElementsBuffer[key].relativeY
    }
  }
  
  animation = new CartoonAnimation(this)
}