package me.lenajenichen.voicebot.listener;

import me.lenajenichen.voicebot.LoggerInit;
import me.lenajenichen.voicebot.mysql.MySQL;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.user.update.UserUpdateDiscriminatorEvent;
import net.dv8tion.jda.api.events.user.update.UserUpdateNameEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;

import java.sql.ResultSet;
import java.sql.SQLException;

public class NameUpdate extends ListenerAdapter {

    @Override
    public void onUserUpdateName(UserUpdateNameEvent e) {
        User user = e.getUser();
        ResultSet getUsername = MySQL.queryMySQL("SELECT user_name FROM createvoice_users WHERE user_id = '" + user.getId() + "'");
        try {
            if(getUsername.next()) {
                MySQL.updateQuery("UPDATE createvoice_users SET user_name = '" + user.getName() + "'");
            } else {
                MySQL.updateQuery("INSERT INTO createvoice_users(user_id, user_name, user_discriminator, avatarURL) VALUES('" + user.getId() + "', '" + user.getName() + "', '" + user.getDiscriminator() + "', '" + user.getAvatarUrl() + "')");
            }
        } catch (SQLException ex) {
            LoggerInit.logger.warning(ex.toString());
        }
    }

    @Override
    public void onUserUpdateDiscriminator(UserUpdateDiscriminatorEvent e) {
        User user = e.getUser();
        ResultSet getDiscriminator = MySQL.queryMySQL("SELECT user_discriminator FROM createvoice_users WHERE user_id = '" + user.getId() + "'");
        try {
            if(getDiscriminator.next()) {
                MySQL.updateQuery("UPDATE createvoice_users SET user_discriminator = '" + user.getDiscriminator() + "'");
            } else {
                MySQL.updateQuery("INSERT INTO createvoice_users(user_id, user_name, user_discriminator, avatarURL) VALUES('" + user.getId() + "', '" + user.getName() + "', '" + user.getDiscriminator() + "', '" + user.getAvatarUrl() + "')");
            }
        } catch (SQLException ex) {
            LoggerInit.logger.warning(ex.toString());
        }
    }

}
