package com.fp.persistence.commondb.helper;

import javax.persistence.Query;

import com.fp.common.helper.FkException;
import com.fp.persistence.commondb.PersistenceHelper;

/**
 * Clase que entrega la tabla padre y dependiente dado un foreing key.
 * 
 * @author Jorge Vaca
 * @version 2.1
 */
public class Fkconstraint implements FkException {

    @Override
    public String[] getFkData(String pFk) {
        try {
            String parent = this.getParentTable(pFk);
            String child = this.getChildTable(pFk);
            String[] data = new String[2];
            data[0] = parent;
            data[1] = child;
            return data;
        } catch (Exception e) {
            // No tomar accion.
        }
        return null;
    }

    private String getParentTable(String pFk) throws Exception {
        String table = null;
        Query qry = PersistenceHelper.getEntityManager().createNativeQuery(Fkconstraint.SQL);
        qry.setParameter("fk", pFk);
        table = (String) qry.getSingleResult();
        return table;
    }

    private String getChildTable(String pFk) throws Exception {
        String table = null;
        // SQLQuery qry = pSession.createSQLQuery(Fkconstraint.SQL_DEP);
        Query qry = PersistenceHelper.getEntityManager().createNativeQuery(Fkconstraint.SQL_DEP);
        qry.setParameter("fk", pFk);
        table = (String) qry.getSingleResult();
        return table;
    }

    private static final String SQL = "select  table_name from user_constraints where constraint_name = ( "
            + "select unique r_constraint_name from all_constraints where constraint_name = :fk)";

    private static final String SQL_DEP = "select table_name from user_constraints where constraint_name  = :fk";

}
