package me.lenajenichen.voicebot.listener;

import me.lenajenichen.voicebot.LoggerInit;
import me.lenajenichen.voicebot.api.CreateCaptchaImage;
import me.lenajenichen.voicebot.api.CreateDescription;
import me.lenajenichen.voicebot.mysql.MySQL;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberLeaveEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.Date;

public class GuildMemberJoin extends ListenerAdapter {

    @Override
    public void onGuildMemberJoin(GuildMemberJoinEvent e) {
        User user = e.getUser();
        System.out.println("1");
        ResultSet getUser = MySQL.queryMySQL("SELECT user_id FROM createvoice_users WHERE user_id = '" + user.getId() + "'");
        ResultSet getUserCaptcha = MySQL.queryMySQL("SELECT user_id FROM createvoice_captchas WHERE user_id = '" + user.getId() + "'");
        try {
            System.out.println("1");
            if (!(getUser.next())) {
                System.out.println("2");
                MySQL.updateQuery("INSERT INTO createvoice_users(user_id, user_name, user_discriminator, avatarURL) VALUES('" + user.getId() + "', '" + user.getName() + "', '" + user.getDiscriminator() + "', '" + user.getAvatarUrl() + "')");
            } else if (!getUserCaptcha.next()) {
                MySQL.updateQuery("INSERT INTO createvoice_captchas(guild_id, message_id, message_id_teamchat, user_id, code, attempts, kicks) VALUES('" + " " + "', '" + " " + "', '" + " " + "', '" + user.getId() + "', '" + " " + "', '" + 0 + "', '" + 0 + "')");
            }
            System.out.println("1");
        } catch (SQLException ex) {
            LoggerInit.logger.warning(ex.toString());
        }
        System.out.println("1");
        Date date = new Date();
        String now = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(new Date());
        System.out.println("1");
        int createdyear = e.getUser().getTimeCreated().getYear();
        int createdmonth = e.getUser().getTimeCreated().getMonthValue();
        int monthsago = date.getMonth() - createdmonth;
        if(monthsago <= 1) {
            System.out.println("3");
            ResultSet getLogChannel = MySQL.queryMySQL("SELECT channel_id FROM createvoice_teamchat WHERE guild_id = '" + Long.valueOf(e.getGuild().getId()) + "'");
            try {
                System.out.println("3");
                if(getLogChannel.next()) {
                    System.out.println("3");
                    Long logchannel_id = getLogChannel.getLong("channel_id");
                    System.out.println("3");
                    ResultSet getGuildID = MySQL.queryMySQL("SELECT guild_id FROM createvoice_teamchat WHERE channel_id ='" + logchannel_id + "'");
                    if (getGuildID.next()) {
                        System.out.println("3");
                        Long guildID = getGuildID.getLong("guild_id");
                        System.out.println("3");
                        TextChannel logchannel = e.getJDA().getGuildById(guildID).getTextChannelById(logchannel_id);
                        System.out.println("3");
                        ResultSet getAvatarURL = MySQL.queryMySQL("SELECT avatarURL FROM createvoice_users WHERE user_id = '" + user.getId() + "'");
                        if (getAvatarURL.next()) {
                            System.out.println("3");
                            ResultSet getUsername = MySQL.queryMySQL("SELECT user_name FROM createvoice_users WHERE user_id = '" + user.getId() + "'");
                            if (getUsername.next()) {
                                System.out.println("3");
                                ResultSet getKicks = MySQL.queryMySQL("SELECT kicks FROM createvoice_captchas WHERE user_id = '" + user.getId() + "'");
                                if (getKicks.next()) {
                                    System.out.println("3");
                                    int kicks = getKicks.getInt("kicks");
                                    String username = getUsername.getString("user_name");
                                    String URL = getAvatarURL.getString("avatarURL");
                                    if (URL.equalsIgnoreCase("null")) {
                                        System.out.println("3");
                                        CreateDescription.createDescriptionTitleAuthorMessageFooterSQL("Es wurde ein neuer Account gefunden. Die Person hat nun eine recaptcha erhalten und wird diese Ausfüllen müssen.\n\nVersuche: 0/3 | Kicks: " + kicks + "/3", "#FFFF00", logchannel, "http://195.90.201.89/images/default_discord_pfp.jpg", "Suspicious account found!", username, now);
                                    } else {
                                        System.out.println("4");
                                        CreateDescription.createDescriptionTitleAuthorMessageFooterSQL("Es wurde ein neuer Account gefunden. Die Person hat nun eine recaptcha erhalten und wird diese Ausfüllen müssen.\n\nVersuche: 0/3 | Kicks: " + kicks + "/3", "#FFFF00", logchannel, URL, "Suspicious account found!", username, now);
                                    }
                                    System.out.println("3");
                                    CreateCaptchaImage.create();
                                    CreateDescription.createDescriptionPrivateMemberMessageTitle(e.getMember(), "Wir haben festgestellt das dein Account erst vor kurzem erstellt wurde, um Bot zu verhindern haben wir für neue neu erstellte Discord Account eine recaptcha um sicher zu gehen das es kein Bot ist. Du hast insgesamt 3 Versuche diese recaptcha zu schaffen, schaffst du es nicht wirst du gekickt und du kannst es nocheinmal versuchen. Beim 3ten kick wirst du automatisch gebannt da wir davon ausgehen das du ein Bot bist. Wenn du dies verstanden hast schreibe bitte den unten zu sehenden Code.", "#F6DF13", "Verdächtiger Account", "http://195.90.201.89/images/captcha.png");
                                    MySQL.updateQuery("UPDATE createvoice_captchas SET guild_id = '" + e.getGuild().getId() + "', code = '" + CreateCaptchaImage.getCode() + "' WHERE user_id = '" + e.getUser().getId() + "'");
                                }
                            }
                        }
                    }
                }
            } catch (SQLException exception) {
                exception.printStackTrace();
            } catch (IOException ioException) {
                LoggerInit.logger.warning(ioException.getStackTrace().toString());
            }
        }


        Year year = Year.now().minusYears(createdyear);
        @SuppressWarnings("deprecation")
        int month = date.getMonth() - createdmonth;
    }

    @Override
    public void onGuildMemberLeave(GuildMemberLeaveEvent e) {
        User user = e.getUser();
        MySQL.updateQuery("DELETE FROM createvoice_users WHERE user_id = '" + user.getId() + "'");
    }

}
