package com.cogix.vwf;

import javax.servlet.*;
import java.sql.*;

public class DBLookupRole extends RoleLookup {

    //  Test table created with
    //  CREATE TABLE VWFUSERROLES ( VFUSER VARCHAR (32) NOT NULL, VFROLE VARCHAR (32) NOT NULL );
    //  CREATE INDEX USERINDEX ON VWFUSERROLES (VFUSER);
    //  CREATE INDEX ROLEINDEX ON VWFUSERROLES (VFROLE);

    //  Customize the following line
    private static final String userinroleQuery
            = "SELECT COUNT(*) FROM VWFUSERROLES WHERE VFUSER ='%1' AND VFROLE='%2'";

    void init() throws UnavailableException {
        if ( Dirs.getdbStore() == null )
            throw new UnavailableException ("Database connector not available");
    }

    //  Query: select count(*) from tablename where userid=userid and role=role

    //  Extensions must use userid explicitly, not tc.getremoteuser!
    //  ThisCall is available in case it's needed
    //  Let it throw any errors encountered
    boolean bIsUserInRole(ThisCall tc, String userid, String role) throws Exception {
        Statement stmt = null;
        ResultSet rs = null;
        int count = -1;
        String query = userinroleQuery;
        dbStore dbs = Dirs.getdbStore();
        Connection con = null;
        try {
            if ( Misc.isEmpty (userid) || Misc.isEmpty (role) )
                return false;

            query = Misc.stringReplace ( userinroleQuery, "%1", userid );
            query = Misc.stringReplace ( query, "%2", role );

            con = dbs.getConnection();  //  from pool
            stmt = con.createStatement();
            rs = stmt.executeQuery (query);
            if ( rs.next() ) {
                count = rs.getInt (1);
                return count > 0;
            }
        } catch (Throwable e) {
            //  To disable logging, remove this:
            Dirs.WriteLog ("631I","Exception looking up user in role with " + query + ": " + e.toString() );
            return false;
        } finally {
            if ( rs != null ) try { rs.close(); } catch (Exception ignored) {}
            if ( stmt != null ) try { stmt.close(); } catch (Exception ignored) {}
            dbs.freeConnection (con);   //  back to pool, null is ok

            if ( Dirs.bLogRequests3 () ) {
                String msg = "DBLookupRole.bIsUserInRole: " + query + " returned " + count ;
                Dirs.WriteLog ("667I", msg );
            }

        }
        return false;
    }

}
