001/*
002 * Trident - A Multithreaded Server Alternative
003 * Copyright 2014 The TridentSDK Team
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package net.tridentsdk.server.service;
018
019import com.google.common.collect.ForwardingCollection;
020import net.tridentsdk.Trident;
021import net.tridentsdk.entity.living.Player;
022import net.tridentsdk.plugin.Plugin;
023import net.tridentsdk.service.ChatFormatter;
024import net.tridentsdk.service.ChatIdentityFormatter;
025import net.tridentsdk.util.TridentLogger;
026
027import java.util.Collection;
028import java.util.Collections;
029
030/**
031 * Handles the chat formatting
032 *
033 * @author The TridentSDK Team
034 */
035public class ChatHandler
036        extends ForwardingCollection<ChatIdentityFormatter>
037        implements ChatFormatter {
038    private volatile ChatIdentityFormatter provider = new ChatIdentityFormatter() {
039        @Override
040        public String format(String message, Player sender) {
041            return "%n%d";
042        }
043
044        @Override
045        public void overriden(ChatIdentityFormatter other, Plugin overrider) {
046            TridentLogger.get().warn("Trident default chat overriden by " + overrider);
047        }
048    };
049
050    public ChatHandler() {
051        if (!Trident.isTrident())
052            throw new RuntimeException(new IllegalAccessException("This class should only be instantiated by Trident"));
053    }
054
055    @Override
056    public void setFormatter(ChatIdentityFormatter provider, Plugin plugin) {
057        this.provider.overriden(provider, plugin);
058        this.provider = provider;
059    }
060
061    @Override
062    public String format(String message, Player player) {
063        return provider.format(message, player);
064    }
065
066    @Override
067    protected Collection<ChatIdentityFormatter> delegate() {
068        return Collections.singleton(provider);
069    }
070}