package com.persagy.adm.diagram.core.model.base;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.gson.annotations.Expose;

import java.util.HashMap;
import java.util.Map;

/**
 * 布局和绘制组件的基类
 * @author zhaoyk
 */
abstract public class AbstractComponent implements IComponent {

	@Expose //使用gson保存文件
	protected String id;

	@Expose
	protected String name;

	@Expose
	protected String compType;

	@JsonIgnore //使用jackson输出到web端
	protected IContainer parent;

	@Expose
	protected PositionData position;

	/**
	 * 布局定位
	 */
	protected XY location;

	/**
	 * 布局尺寸
	 */
	protected XY size;

	/**
	 * 组件的显示/隐藏状态
	 */
	protected boolean hidden;

	/**
	 * 属性
	 */
	@Expose
	private Map<String, Object> props;

	protected AbstractComponent(){

	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public void setId(String id) {
		this.id = id;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String getCompType() {
		return compType;
	}

	@Override
	public IContainer getParent() {
		return parent;
	}

	@Override
	public void setParent(IContainer parent) {
		this.parent = parent;
	}

	@Override
	public PositionData getPosition() {
		return position;
	}

	@Override
	public void setPosition(PositionData position) {
		this.position = position;
	}

	@Override
	public PositionData defaultPosition(){
		return null;
	}

	@Override
	public boolean isAbsolutePosition(){
		return position != null && position.isAbsolute();
	}

	@Override
	public XY getLocation() {
		return location;
	}

	@Override
	public void setLocation(XY location) {
		this.location = location;
	}

	@Override
	public XY getSize() {
		return size;
	}

	public void setSize(XY size) {
		this.size = size;
	}

	@Override
	public boolean isHidden() {
		return hidden;
	}

	public void setHidden(boolean hidden) {
		this.hidden = hidden;
	}

	public Object getProp(String name){
		return props != null ? props.get(name) : null;
	}

	public void setProp(String name, Object value){
		if (props == null)
			props = new HashMap<>();
		props.put(name, value);
	}

	public void removeProp(String name) {
		if (props != null) {
			props.remove(name);
			if (props.size() == 0)
				props = null;
		}
	}

	public void setProps(Map<String, Object> props) {
		this.props = props;
	}

	/**
	 * 相对根容器的坐标位置
	 */
	public XY locationToRoot(){
		XY p = new XY(0, 0);
		IComponent c = this;
		while (c != null){
			XY pos = c.getLocation();
			if(pos == null)
				return null;

			p.x += pos.x;
			p.y += pos.y;

			c = c.getParent();
		}
		return p;
	}

}
