import * as d3 from 'd3';
import { globalSetting } from '../global';
import { NetlistRender } from '.';
import { getMarginParamter, LAYOUT_CONSTANT } from './layout';

export class ConnectionRender {
    /**
     * @param {d3.Selection} selection
     * @param {NetlistRender} rootRender
     */
    constructor(selection, rootRender) {
        this.parentSelection = selection;
        this.rootRender = rootRender;
        
        /**
         * @type {BasicD3DataItem[]}
         */
        this.data = [];

        /**
         * @description id 到管理数据项的映射
         * @type {Map<string, BasicD3ManagmentItem[]>}
         */
        this.id2manager = rootRender.id2manager;
    }

    /**
     * @description 将 elknode 关于 constant 的数据添加为 d3 数据项目
     * @param {import('../jsdoc').ElkNode} node 当前的实体（port/例化模块/器件）
     */
    addAsD3DataItem(port, node) {
        const marginParamter = getMarginParamter(port);
        const marginOffset = port.direction === 'input' ? marginParamter.leftMargin: - marginParamter.rightMargin;
        
        this.data.push({
            id: port.id,
            x: port.x + node.x + marginOffset,
            y: port.y + node.y + 0.5,       // 0.5 是为了线宽
            width: port.width,
            height: port.height,
            fill: 'var(--main-color)',
            text: '',
            r: 3.5
        });
    }

    render() {
        const data = this.data;
        const id2manager = this.id2manager;
        const _this = this;

        let connectionSelections = this.parentSelection.selectAll('circle')
            .data(data, d => d.id)
            .enter()
            .append('circle')
            .attr('cx', data => data.x)
            .attr('cy', data => data.y)
            .attr('width', data => data.width)
            .attr('height', data => data.height)
            .attr('fill', d => d.fill)
            .attr('r', d => d.r)
            .each(function (data) {
                const selection = d3.select(this);                
                // const manager = _this.createDataManager(selection, data);
            });

        this.selections = connectionSelections;
        return connectionSelections;
    }

    /**
     * 
     * @param {d3.Selection} selection 
     * @param {BasicD3DataItem} data 
     * @returns {BasicD3ManagmentItem}
     */
    createDataManager(selection, data) {
        const id2manager = this.id2manager;
        // connection 不需要拖拽上下文
        const managerItem = {
            data,
            selection,
            type: 'connection'
        };

        if (!id2manager.has(data.id)) {
            id2manager.set(data.id, []);
        }

        id2manager.get(data.id).push(managerItem);
        return managerItem;
    }
}
