package microfolie.persistance.table;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;

import db.Database;
import db.DatabaseTable;
import db.SQLQueryBuilder;
import db.annotation.DbTable;
import db.mapper.DatabaseMapper;
import microfolie.persistance.entity.Usager;

@DbTable(name = "Usager", entity = Usager.class)
public class UsagerTable extends DatabaseTable<Usager> {
	
	private static final Logger LOGGER = Logger.getLogger(UsagerTable.class.getName());
	private static UsagerTable instance;
	
	private UsagerTable() {
		// Private constructor for singleton
	}
	
	public Usager getByCode(String code) {
		List<Usager> list = getByField("CODE", code);
		if(list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}
	
	public Optional<Usager> findByCode(String code) {
		Usager obj = getByCode(code);
		if (obj == null) {
			return Optional.empty();
		}
		return Optional.of(obj);
	}
	
	public boolean codeIsUnique(String code) {
		return !findByCode(code).isPresent();
	}
	
	public long getNumberUsagerInDatabase() {
		Optional<Long> opt = Database.query("Select count(*) From Usager", rs -> {
			try {
				rs.next();
				return rs.getLong(1);
			} catch (SQLException e) {
				LOGGER.warning(e.getMessage());
				return 0l;
			}
		});
		if (opt.isPresent()) {
			return opt.get();
		}
		return 0l;
	}
	
	public List<Usager> getpage(int num, int perPage) {
		SQLQueryBuilder sqlBuilder = SQLQueryBuilder.selectQuery("(Select ROW_NUMBER() OVER() as rownum, Usager.* From Usager) as tmp");
		String sql = sqlBuilder.getSQL("And rownum > ? And rownum <= ?");
		List<Object> params = sqlBuilder.getParams();
		params.add(perPage * (num - 1));
		params.add(perPage * num);
		Optional<List<Usager>> opt = Database.query(sql, params, DatabaseMapper.listMapper(getClass().getAnnotation(DbTable.class)));
		if (opt.isPresent()) {
			return cache(opt.get());
		}
		return new ArrayList<>();
	}
	
	public static UsagerTable getInstance() {
		if(instance == null) {
			instance = new UsagerTable();
		}
		return instance;
	}	

}
