package com.brilliance.mda.runtime.mda.impl;

import com.brilliance.mda.runtime.mda.*;
import com.brilliance.mda.runtime.mda.util.RuleUtils;
import org.apache.poi.poifs.macros.Module;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author s_guodong
 * @Date 2022/11/15
 */
public abstract class AbstractBaseObject implements IBaseObject {
    protected transient List<IRule> defaultRules = null;

    protected transient IParent parent;

    protected transient long key = -1L;

    protected transient String name;

    protected transient String url;

    protected transient boolean sorted = false;

    protected transient boolean disposed = false;

    public AbstractBaseObject(IParent parent) {
        this.parent = parent;
    }

    public synchronized void dispose() {
        if (this.disposed)
            return;
        if (this.defaultRules != null)
            this.defaultRules.clear();
        this.defaultRules = null;
        this.parent = null;
        this.name = null;
        this.url = null;
        this.disposed = true;
        try {
            finalize();
        } catch (Throwable throwable) {}
    }

    public boolean isDisposed() {
        return this.disposed;
    }

    public abstract void clear();

    public long getIdAttributeKey() {
        return this.key;
    }

    public void setIdAttributeKey(long key) {
        this.key = key;
    }

    public Object setAttribute(String name, Object attribute) {
        if (this instanceof IParent)
            return ((IParent)this).setAttribute(this, name, attribute);
        return this.parent.setAttribute(this, name, attribute);
    }

    public Object getAttribute(String name) {
        if (this instanceof IParent)
            return ((IParent)this).getAttribute(this, name);
        if (this.parent == null)
            System.out.println(getUrl());
        return this.parent.getAttribute(this, name);
    }

    public IModule getParent() {
        return (IModule)this.parent;
    }

    public String getName() {
        return this.name;
    }

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

    public String getUrl() {
        return this.url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void addDefaultRule(IRule rule) {
        if (this.defaultRules == null)
            this.defaultRules = new ArrayList<IRule>();
        this.defaultRules.add(rule);
    }

    protected void sort() {
        this.sorted = true;
        RuleUtils.sort(this.defaultRules);
    }

    public boolean invokeDefaultRules(IContext ctx) {
        if (!this.sorted)
            sort();
        return RuleUtils.invoke(this.defaultRules, ctx, null);
    }
}
