import { Vector3, Line, BufferGeometry, LineBasicMaterial } from 'three';

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}

/**
 * mitt 事件总程
 */
class MyMitt {
    constructor() {
        Object.defineProperty(this, "emitter", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: mitt()
        });
    }
    on(type, handler) {
        this.emitter.on(type, handler);
        return this;
    }
    off(type, handler) {
        this.emitter.off(type, handler);
        return this;
    }
}

/**
 * 基类，element
 *
 * 被添加到地图上的元素
 *
 * 若当前扩展类不需要 mitt，在继承时，泛型填写 any，如：
 *
 * ```ts
 * class Foo extends Element<any>{
 *
 * }
 * ```
 */
class Element extends MyMitt {
    constructor() {
        super();
        /**
         * NAME
         * 一般为子类的类名（防止工具压缩把类名压缩了，导致一些拿类名判断的逻辑失效，所以手动加上类名）
         */
        // abstract NAME: string;
        Object.defineProperty(this, "map", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
    }
    /**
     * __inject
     * 当元素被 map.add 之后，会注入整个 map 对象到子类，提供子类使用 map
     */
    __inject(map) {
        this.map = map;
        return this;
    }
}

/**
 *
 */
class RoadNetLayer extends Element {
    constructor(options) {
        super();
        Object.defineProperty(this, "options", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: options
        });
    }
    __init() {
        console.log('RoadNetLayer init success');
        this.initData(this.drawRoadNet.bind(this));
    }
    /**
     * TODO:待优化提取
     */
    initData(cb) {
        return __awaiter(this, void 0, void 0, function* () {
            const { data } = this.options;
            if (typeof data === 'function') {
                try {
                    const res = yield data();
                    console.log('resresresres :>> ', res);
                    cb === null || cb === void 0 ? void 0 : cb(res);
                    // for (const fn of this.completeCbs) fn?.({ data: res, foo: 1, bar: 2 });
                }
                catch (_) { }
            }
            else {
                cb === null || cb === void 0 ? void 0 : cb(data);
                // for (const fn of this.completeCbs) fn?.({ data, foo: 1, bar: 2 });
            }
        });
    }
    /**
     * 拿到路网数据，绘制基础路网
     */
    drawRoadNet(data) {
        const { map } = this;
        for (const item of data) {
            item.begin[0] = +item.begin[0];
            item.begin[1] = +item.begin[1];
            item.end[0] = +item.end[0];
            item.end[1] = +item.end[1];
            const { begin, end, id } = item;
            this.drawNormalLine(
            // TODO：地板高度为1000，后续规范到 @shared 包的通用配置
            [new Vector3(...begin, 0), new Vector3(...end, 0)], {
                name: 'ar_roadNetPath',
                color: 'red'
            });
        }
        map.reDraw();
    }
    /**
     * 绘制普通线段
     */
    drawNormalLine(points, 
    // end: [number, number],
    ext) {
        const { map } = this;
        const line = new Line(new BufferGeometry().setFromPoints(points), new LineBasicMaterial({
            // visible: false,
            color: (ext === null || ext === void 0 ? void 0 : ext.color) || 'red',
            opacity: 1,
            transparent: true,
            depthTest: false
        }));
        line.name = (ext === null || ext === void 0 ? void 0 : ext.name) || '';
        // line.renderOrder = 998;
        line.userData = {
        // id,
        // begin,
        // end
        };
        map.scene.add(line);
    }
}
Object.defineProperty(RoadNetLayer, "NAME", {
    enumerable: true,
    configurable: true,
    writable: true,
    value: 'RoadNetLayer'
});

export { RoadNetLayer };
