package com.acme.model.domain.ad.entity;


import com.acme.structure.BaseEntity;
import com.acme.structure.BaseEntityListener;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;


@Entity(name = "Branch")
@Table(name = "BRANCHES")
//this is for oracle db @SequenceGenerator(name = "BRANCH_SEQ", sequenceName = "BRANCH_SEQ", allocationSize = 1)
@EntityListeners( { BaseEntityListener.class })
public class Branch extends BaseEntity
{
    private String code;
    private String name;
    private Collection<Department> departments;

    public Branch()
    {
        entityName = "Branch";
        departments = new ArrayList<Department>();
    }

    public Branch(int id, String name)
    {
        entityName = "Branch";
        departments = new ArrayList<Department>();

        this.id = id;
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO) //, this is for oracle db, generator = "BRANCH_SEQ")
    @Column(name = "ID")
    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    @Column(name = "CODE", length = 10)
    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    @Column(name = "NAME", length = 60)
    public String getName()
    {
        return name;
    }

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

    @OneToMany(targetEntity = Department.class, fetch = (FetchType.LAZY), cascade = { CascadeType.ALL })
    @org.hibernate.annotations.Cascade( { org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
    @JoinColumn(name = "BRANCHID")
    public Collection<Department> getDepartments()
    {
        return departments;
    }

    public void setDepartments(Collection<Department> departments)
    {
        this.departments = departments;
    }

    @Override
    @Transient
    public void clearIdFields()
    {
        super.clearIdFields();

        Department department = null;
        Iterator itr = departments.iterator();

        while (itr.hasNext())
        {
            department = (Department)itr.next();
            department.clearIdFields();
        }
    }

    @Override
    public String toString()
    {
        return getCode() + "-" + getName();
    }

}
