package me.km.snuviscript;

import me.hammerle.snuviscript.code.ISnuviLogger;
import me.hammerle.snuviscript.code.Script;
import me.km.permissions.PermissionManager;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.StringTextComponent;

public class SnuviLogger implements ISnuviLogger
{
    private boolean printToConsole = true;
    private MinecraftServer server = null;
    private PermissionManager perms = null;
    
    public void setConsoleLogging(boolean b)
    {
        printToConsole = b;
    }
    
    public void setPlayerLoggingData(MinecraftServer server, PermissionManager perms)
    {
        this.server = server;
        this.perms = perms;
    }
    
    @Override
    public void print(String message, Exception ex, String function, String scriptname, Script sc, int line) 
    {
        StringBuilder sb = new StringBuilder();
        sb.append("[§cLogger§r] ");
        
        String color;
        
        if(ex == null)
        {
            color = "§e";
            sb.append(color);
            sb.append("debug: '§r");
            sb.append(message);
            sb.append(color);
            sb.append("'");
        }
        else
        {
            color = "§c";
            sb.append(color);
            sb.append(ex.getClass().getSimpleName());
            sb.append("§r: '");
            sb.append(color);
            sb.append(ex.getMessage());
            if(message != null && !message.isEmpty())
            {
                sb.append(" - ");
                sb.append(message);
            }
            sb.append("§r'");
        }
        
        if(scriptname != null && !scriptname.isEmpty())
        {
            sb.append(" in script '");
            sb.append(color);
            sb.append(scriptname);
            sb.append("§r'");
        }
        
        if(sc != null)
        {
            sb.append(" id '");
            sb.append(color);
            sb.append(sc.getId());
            sb.append("§r'");
        }
        
        if(function != null && !function.isEmpty())
        {
            sb.append(" in function '");
            sb.append(color);
            sb.append(function);
            sb.append("§r'");
        }
        
        if(line != -1)
        {
            sb.append(" in line '");
            sb.append(color);
            sb.append(line);
            sb.append("§r'");
        }
        
        StringTextComponent text = new StringTextComponent(sb.toString());

        if(printToConsole && server != null)
        {
            server.sendMessage(text);
        }
        
        if(server != null && perms != null && server.getPlayerList() != null)
        {
            server.getPlayerList().getPlayers().forEach(p -> 
            {
                if(perms.hasPermission(p, "script.error"))
                {
                    p.sendMessage(text);
                }
            });
        }
    }
}
