package com.repository.impl;

import com.entity.SignUpUser;
import com.repository.RegistrationRepository;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * Implementation for the registration repository.
 *
 * @author Laurentiu Marcut
 */
public class RegistrationRepositoryImpl extends BaseRepositoryImpl implements RegistrationRepository {

    private static final String SELECT_BY_MAIL = "select * from user where email = ? ";
    private static final String INSERT_USER = "insert into user(email, first_name, last_name, birth_date, password) values(?, ?, ?, ?, ?) ";
    private static final String INSERT_USER_ROLE = "insert into user_role(user, role) values(?, ?) ";

    @Override
    public boolean checkEmail(String email) throws SQLException {
        try (PreparedStatement st = super.getConnection().prepareStatement(RegistrationRepositoryImpl.SELECT_BY_MAIL)) {
            st.setString(1, email);

            try (ResultSet rs = st.executeQuery()) {
                if (rs.next()) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public void insertUser(SignUpUser user) throws SQLException {
        try (PreparedStatement st = super.getConnection().prepareStatement(RegistrationRepositoryImpl.INSERT_USER)) {
            st.setString(1, user.getEmail());
            st.setString(2, user.getFirstName());
            st.setString(3, user.getLastName());
            st.setDate(4, new Date(user.getBirthDate().getTime()));
            st.setString(5, user.getPassword());

            st.executeUpdate();
        }
    }

    @Override
    public void insertUserRole(String email, String role) throws SQLException {
        try (PreparedStatement st = super.getConnection().prepareStatement(RegistrationRepositoryImpl.INSERT_USER_ROLE)) {
            st.setString(1, email);
            st.setString(2, role);

            st.executeUpdate();
        }
    }

}
