package OWL2generator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DeclareSubclasses
{
    DeclareSubclasses(String      OWLresultFile,  //  result file name 
                      Connection  DBconnection
                     )
    {
        int         countOfSubclassDeclarations    = 0 ;
        int         countOfBFOsubclassDeclarations = 0 ;
        DBFO_DButils     dbu                            = new DBFO_DButils() ;
        FileWriter  fileWriter                     = null ;
        SharedUtils shu                            = new SharedUtils() ;
        
        ResultSet rs = dbu.establishResultSet(DBconnection, 
                       "SELECT class_IRI, superclass_of_IRI FROM OWL_CLASSES ORDER BY class_IRI ASC ;") ;
        try 
        {
            fileWriter = new FileWriter(new File(OWLresultFile), true) ;

            fileWriter.write("\n    <!--  subclass declarations\n      -->\n") ;

            while (rs.next()) 
            {
                String superclass_of_IRI = rs.getString("superclass_of_IRI") ;

            	if (superclass_of_IRI.substring(0, 4).compareTo("BFO_") == 0)
            	{
                    fileWriter.write(shu.declareBFOsubClass(superclass_of_IRI,
                                                            rs.getString("class_IRI"))) ;
                    countOfBFOsubclassDeclarations++ ;
            	}
            	else
            	{
            		fileWriter.write(shu.declareSubClass(superclass_of_IRI,
                                                         rs.getString("class_IRI"))) ;
                    countOfSubclassDeclarations++ ;
            	}
            }
            
            /**
             *  closing the result set
             */
            rs.close() ;
            
            /**
             *  closing the file writer
             */
            fileWriter.close() ;
        }
        catch(SQLException SQLex)
        {
            System.out.println("Cannot connect the database") ;
            System.out.println("SQLException: " + SQLex.getMessage());
            System.out.println("SQLState: "     + SQLex.getSQLState());
            System.out.println("VendorError: "  + SQLex.getErrorCode());

            SQLex.printStackTrace();
        }
        catch(IOException IOex)
        {
            IOex.printStackTrace() ;
        }

        /**
         *  Logging of the output volume
         */
        DBFO_main OWL2G = new DBFO_main() ;
        
        OWL2G.log(new StringBuilder()
                      .append("    declared  " + countOfSubclassDeclarations    + " domain ontology subclass(es)\n")
                      .append("    declared  " + countOfBFOsubclassDeclarations + " BFO subclass(es)\n")
                      .toString()
                 ) ; 

    }   //  end of constructor()
        
}   //  end of class DeclareSubclasses
