2018-07-06 15:30:00 +02:00
package com.eu.habbo.habbohotel.catalog ;
2019-07-31 18:01:10 +02:00
import com.eu.habbo.Emulator ;
import java.sql.Connection ;
import java.sql.PreparedStatement ;
2018-07-06 15:30:00 +02:00
import java.sql.ResultSet ;
import java.sql.SQLException ;
2019-07-31 18:01:10 +02:00
import java.util.ArrayList ;
import java.util.List ;
2018-07-06 15:30:00 +02:00
2019-05-26 20:14:53 +02:00
public class Voucher {
2019-03-18 02:22:00 +01:00
public final int id ;
2018-07-06 15:30:00 +02:00
public final String code ;
public final int credits ;
public final int points ;
public final int pointsType ;
public final int catalogItemId ;
2019-07-31 18:01:10 +02:00
public final int amount ;
public final int limit ;
private final List < VoucherHistoryEntry > history = new ArrayList < > ( ) ;
2018-07-08 23:32:00 +02:00
2019-05-26 20:14:53 +02:00
public Voucher ( ResultSet set ) throws SQLException {
this . id = set . getInt ( " id " ) ;
this . code = set . getString ( " code " ) ;
this . credits = set . getInt ( " credits " ) ;
this . points = set . getInt ( " points " ) ;
this . pointsType = set . getInt ( " points_type " ) ;
2018-07-06 15:30:00 +02:00
this . catalogItemId = set . getInt ( " catalog_item_id " ) ;
2019-07-31 18:01:10 +02:00
this . amount = set . getInt ( " amount " ) ;
this . limit = set . getInt ( " limit " ) ;
this . loadHistory ( ) ;
}
private void loadHistory ( ) {
try ( Connection connection = Emulator . getDatabase ( ) . getDataSource ( ) . getConnection ( ) ; PreparedStatement statement = connection . prepareStatement ( " SELECT * FROM voucher_history " ) ) {
try ( ResultSet set = statement . executeQuery ( ) ) {
while ( set . next ( ) ) {
this . history . add ( new VoucherHistoryEntry ( set ) ) ;
}
}
} catch ( SQLException e ) {
Emulator . getLogging ( ) . logSQLException ( e ) ;
}
}
public boolean hasUserExhausted ( int userId ) {
return this . limit > 0 & & Math . toIntExact ( this . history . stream ( ) . filter ( h - > h . getUserId ( ) = = userId ) . count ( ) ) > = this . limit ;
}
public boolean isExhausted ( ) {
return this . amount > 0 & & this . history . size ( ) > = this . amount ;
}
public void addHistoryEntry ( int userId ) {
int timestamp = Emulator . getIntUnixTimestamp ( ) ;
this . history . add ( new VoucherHistoryEntry ( this . id , userId , timestamp ) ) ;
try ( Connection connection = Emulator . getDatabase ( ) . getDataSource ( ) . getConnection ( ) ; PreparedStatement statement = connection . prepareStatement ( " INSERT INTO voucher_history (`voucher_id`, `user_id`, `timestamp`) VALUES (?, ?, ?) " ) ) {
statement . setInt ( 1 , this . id ) ;
statement . setInt ( 2 , userId ) ;
statement . setInt ( 3 , timestamp ) ;
statement . execute ( ) ;
} catch ( SQLException e ) {
Emulator . getLogging ( ) . logSQLException ( e ) ;
}
2018-07-06 15:30:00 +02:00
}
}