package be.jeffcheasey88.peeratcode.bonus.discord;

import java.util.List;

import be.jeffcheasey88.peeratcode.Configuration;
import be.jeffcheasey88.peeratcode.framework.Locker;
import be.jeffcheasey88.peeratcode.framework.Locker.Key;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;

public class Bot extends Thread{
	
	private String token;
	private DatabaseRepository repo;
	private Locker<Group> locker;
	
	public Bot(Configuration config, DatabaseRepository repo, Locker<Group> locker){
		this.token = config.getDiscordToken();
		this.repo = repo;
		this.locker = locker;
	}

	@Override
	public void run(){
		if(token == null) return;
		try{
			JDA jda = JDABuilder.createDefault(token).build();
			jda.awaitReady();
			Guild guild = jda.getGuildById(1068824613603262464L);
			Category event = guild.getCategoryById(1095761356017373284L);

			Key key = new Key();
			
			locker.init(key);
			
			List<Group> groups = this.repo.getAllGroups();
			for(Group group : groups){
				Integer chapter = group.getLinkToChapter();
//				Integer puzzle = group.getLinkToPuzzle();
				if((chapter == null || chapter == 0)) continue;
				boolean contains = false;
				for(VoiceChannel channel : event.getVoiceChannels()){
					if(channel.getName().equalsIgnoreCase(group.getName())){
						contains = true;
						break;
					}
				}
				if(contains) continue;
				event.createVoiceChannel(group.getName()).complete();
			}
			
			while(true){
				locker.lock(key);
				Group group = locker.getValue(key);
				Integer chapter = group.getLinkToChapter();
//				Integer puzzle = group.getLinkToPuzzle();
				if((chapter == null || chapter == 0)) continue;
				boolean contains = false;
				for(VoiceChannel channel : event.getVoiceChannels()){
					if(channel.getName().equalsIgnoreCase(group.getName())){
						contains = true;
						break;
					}
				}
				if(contains) continue;
				event.createVoiceChannel(group.getName()).complete();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
