package com.txtr.hibernatedelta.model;

import static javax.xml.bind.annotation.XmlAccessType.FIELD;

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

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;

import org.apache.commons.lang3.StringUtils;

@XmlAccessorType(FIELD)
@XmlType(propOrder = {"name", "columns", "explicitIndexes"})
public class HibernateTable implements IHibernateDatabaseObject {

    @XmlAttribute
    private String name;

    @XmlElementWrapper(name = "columns")
    @XmlElement(name = "column")
    private List<HibernateColumn> columns = new ArrayList<HibernateColumn>();

    @XmlElementWrapper(name = "indexes")
    @XmlElement(name = "index")
    private List<ExplicitHibernateIndex> explicitIndexes = new ArrayList<ExplicitHibernateIndex>();

    @XmlAttribute
    private String sequenceName;

    @XmlAttribute
    private boolean virtualRootTable;

    public HibernateTable(String name, String sequenceName, boolean virtualRootTable) {
        this.sequenceName = sequenceName;
        this.virtualRootTable = virtualRootTable;
        this.name = name;
    }

    @SuppressWarnings("UnusedDeclaration")
    public HibernateTable() {
    }

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

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

    public List<HibernateColumn> getColumns() {
        return columns;
    }

    public List<ExplicitHibernateIndex> getExplicitIndexes() {
        return explicitIndexes;
    }

    public void addColumn(HibernateColumn column) {
        columns.add(column);
    }

    public HibernateColumn getColumn(String name) {
        for (HibernateColumn column : columns) {
            if (column.getName().equalsIgnoreCase(name)) {
                return column;
            }
        }
        throw new IllegalArgumentException("column not found: " + name);
    }

    public void addExplicitIndex(ExplicitHibernateIndex hibernateIndex) {
        explicitIndexes.add(hibernateIndex);
    }

    public String getIndexPrefix() {
        return StringUtils.left(name, 28);
    }

    public List<HibernateColumn> getPrimaryKeyColumns() {
        List<HibernateColumn> result = new ArrayList<HibernateColumn>();
        for (HibernateColumn column : columns) {
            if (column.isPrimaryKey()) {
                result.add(column);
            }
        }
        return result;
    }

    public String getSequenceName() {
        return sequenceName;
    }

    public boolean isVirtualRootTable() {
        return virtualRootTable;
    }
}
