/*
 * Copyright (c) 2018, Adam <Adam@sigterm.info>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package net.runelite.client.plugins.twitch;

import com.google.inject.Provides;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.events.ConfigChanged;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.chat.ChatboxInputListener;
import net.runelite.client.chat.CommandManager;
import net.runelite.client.chat.QueuedMessage;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ChatboxInput;
import net.runelite.client.events.PrivateMessageInput;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.twitch.irc.TwitchIRCClient;
import net.runelite.client.plugins.twitch.irc.TwitchListener;
import net.runelite.client.task.Schedule;

@PluginDescriptor(
	name = "Twitch",
	description = "Integrates Twitch chat",
	enabledByDefault = false
)
@Slf4j
public class TwitchPlugin extends Plugin implements TwitchListener, ChatboxInputListener
{
	@Inject
	private TwitchConfig twitchConfig;

	@Inject
	private Client client;

	@Inject
	private ChatMessageManager chatMessageManager;

	@Inject
	private CommandManager commandManager;

	private TwitchIRCClient twitchIRCClient;

	@Override
	protected void startUp()
	{
		connect();
		commandManager.register(this);
	}

	@Override
	protected void shutDown()
	{
		if (twitchIRCClient != null)
		{
			twitchIRCClient.close();
			twitchIRCClient = null;
		}

		commandManager.unregister(this);
	}

	@Provides
	TwitchConfig provideConfig(ConfigManager configManager)
	{
		return configManager.getConfig(TwitchConfig.class);
	}

	private void connect()
	{
		if (twitchConfig.username() != null
			&& twitchConfig.oauthToken() != null
			&& twitchConfig.channel() != null)
		{
			String channel = twitchConfig.channel().toLowerCase();
			if (!channel.startsWith("#"))
			{
				channel = "#" + channel;
			}

			twitchIRCClient = new TwitchIRCClient(
				this,
				twitchConfig.username(),
				twitchConfig.oauthToken(),
				channel
			);
			twitchIRCClient.start();
		}
	}

	@Schedule(period = 30, unit = ChronoUnit.SECONDS, asynchronous = true)
	public void checkClient()
	{
		if (twitchIRCClient != null)
		{
			if (twitchIRCClient.isConnected())
			{
				twitchIRCClient.pingCheck();
			}

			if (!twitchIRCClient.isConnected())
			{
				log.debug("Reconnecting...");

				connect();
			}
		}
	}

	@Subscribe
	public void onConfigChanged(ConfigChanged configChanged)
	{
		if (!configChanged.getGroup().equals("twitch"))
		{
			return;
		}

		if (twitchIRCClient != null)
		{
			twitchIRCClient.close();
			twitchIRCClient = null;
		}

		connect();
	}

	private void addChatMessage(String sender, String message)
	{
		String chatMessage = new ChatMessageBuilder()
			.append(ChatColorType.NORMAL)
			.append(message)
			.build();

		chatMessageManager.queue(QueuedMessage.builder()
			.type(ChatMessageType.CLANCHAT)
			.sender("Twitch")
			.name(sender)
			.runeLiteFormattedMessage(chatMessage)
			.build());
	}

	@Override
	public void privmsg(Map<String, String> tags, String message)
	{
		if (client.getGameState() != GameState.LOGGED_IN)
		{
			return;
		}

		String displayName = tags.get("display-name");
		addChatMessage(displayName, message);
	}

	@Override
	public void roomstate(Map<String, String> tags)
	{
		log.debug("Room state: {}", tags);
	}

	@Override
	public void usernotice(Map<String, String> tags, String message)
	{
		log.debug("Usernotice tags: {} message: {}", tags, message);

		if (client.getGameState() != GameState.LOGGED_IN)
		{
			return;
		}

		String sysmsg = tags.get("system-msg");
		addChatMessage("[System]", sysmsg);
	}

	@Override
	public boolean onChatboxInput(ChatboxInput chatboxInput)
	{
		String message = chatboxInput.getValue();
		if (message.startsWith("//"))
		{
			message = message.substring(2);
			if (message.isEmpty() || twitchIRCClient == null)
			{
				return true;
			}

			twitchIRCClient.privmsg(message);
			addChatMessage(twitchConfig.username(), message);

			return true;
		}
		return false;
	}

	@Override
	public boolean onPrivateMessageInput(PrivateMessageInput privateMessageInput)
	{
		return false;
	}
}

@@ -3326,24 +3326,37 @@
 %7D%0A%0A%09private 
+synchronized 
 void connect
@@ -3604,32 +3604,174 @@
  channel;%0A%09%09%09%7D%0A%0A
+%09%09%09log.debug(%22Connecting to Twitch as %7B%7D%22, twitchConfig.username());%0A%0A%09%09%09if (twitchIRCClient != null)%0A%09%09%09%7B%0A%09%09%09%09twitchIRCClient.close();%0A%09%09%09%7D%0A%0A
 %09%09%09twitchIRCClie
@@ -4393,103 +4393,8 @@
 %09%7D%0A%0A
-%09%09if (twitchIRCClient != null)%0A%09%09%7B%0A%09%09%09twitchIRCClient.close();%0A%09%09%09twitchIRCClient = null;%0A%09%09%7D%0A%0A
 %09%09co

fix race in connect establishing multiple connections