import { Element } from "../class/Element";
import { Pool } from "../Pool";
import { RecoverName } from "../enum/RecoverName";
import { BitmapRecycle } from "../class/BitmapRecycle";
import { RES } from "../../../module/RES";

const pi = Math.PI;
const pi2 = pi * 2;
/**
 * 一个元素绕一定点旋转，螺旋线
 * 不想写类，写个function得了
 * @param ele 要旋转得元素
 * @param p 位置点
 * @param callback 
 */
export function MagicRotateAni(ele: Element, p: number[], con: FYGE.Container) {
    //弄一个替代的
    let eleC: BitmapRecycle = Pool.takeOut(RecoverName.BITMAPRECYCLE);
    var texture: FYGE.Texture = RES.getRes("ele" + ele.type + ".png");
    if (!eleC) {
        eleC = new BitmapRecycle(texture)
    } else {
        eleC.reset(texture)
    }

    eleC.x = ele.x;
    eleC.y = ele.y;
    con.addChild(eleC);
    var tAll = 60;
    var deltaX = eleC.x - p[0];
    var deltaY = eleC.y - p[1];
    var dis = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    //算角度，弧度，x正方向为0，0到2pi，逆时针为正
    var vec0 = [1, 0]
    var vec1 = [deltaX, deltaY]
    var rotation = getRotByTwoVectors(vec0, vec1);
    if (deltaY > 0) {
        rotation = pi2 - rotation;
    }
    var a = { t: 0 };
    FYGE.Tween.get(a, {
        onChange: function () {
            //螺旋半径，时间t的函数，越来越小，0
            var r = dis * (1 - a.t / tAll);
            //螺旋角度，基础角度+补间角度，
            var theta = a.t / tAll * pi
            var x = r * Math.cos(theta)
            var y = r * Math.sin(theta)
            //旋转一下
            var xy = rotationAcodPoint([x, y], rotation);
            eleC.x = xy[0] + p[0];
            eleC.y = xy[1] + p[1];
            eleC.alpha = eleC.scaleX = eleC.scaleY = 1 - a.t / tAll;
        }
    })
        .to({ t: 60 }, 800, FYGE.Ease.quadIn)
        .call(() => {
            //回收
            con.removeChild(eleC);
            Pool.recover(RecoverName.BITMAPRECYCLE, eleC);
        })
}

/**
 * 
 * @param p 旋转点
 * @param rotation 弧度，逆时针
 * @param point 定点,默认0，0
 */
function rotationAcodPoint(p: number[], rotation: number, point: number[] = [0, 0]) {
    //平移
    var xp = p[0] - point[0];
    var yp = p[1] - point[1];
    //旋转
    var x = xp * Math.cos(rotation) + yp * Math.sin(rotation);
    var y = yp * Math.cos(rotation) - xp * Math.sin(rotation);
    return [x, y]
}

/**
 * 求向量夹角
 * @param vec1 
 * @param vec2 
 */
export function getRotByTwoVectors(vec1: number[], vec2: number[]) {
    var a = Math.sqrt(vec1[0] * vec1[0] + vec1[1] * vec1[1])
    var b = Math.sqrt(vec2[0] * vec2[0] + vec2[1] * vec2[1])
    var ab = vec1[0] * vec2[0] + vec1[1] * vec2[1]
    var cos = ab / (a * b);//反余弦函数范围0到pi
    return Math.acos(cos);
}