/*
 * Copyright (c) 2013 L2jMobius
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.l2jmobius.gameserver.managers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.l2jmobius.commons.database.DatabaseFactory;
import org.l2jmobius.commons.threads.ThreadPool;
import org.l2jmobius.gameserver.config.custom.FakePlayersConfig;

/**
 * Long term memory of fake players about real players.
 * A bot remembers who killed it, who helped it and what was said, and this
 * memory changes both its LLM persona and its template line selection.
 * @author Mobius SPP
 */
public class FakePlayerMemoryManager
{
	private static final Logger LOGGER = Logger.getLogger(FakePlayerMemoryManager.class.getName());
	
	public static class Memory
	{
		public int score = 0;
		public int kills = 0;
		public int helps = 0;
		public String note = "";
		public long updated = 0;
		boolean dirty = false;
	}
	
	private final Map<Integer, Map<String, Memory>> _memories = new ConcurrentHashMap<>();
	
	protected FakePlayerMemoryManager()
	{
		if (!FakePlayersConfig.FAKE_PLAYERS_ENABLED)
		{
			return;
		}
		
		try (Connection con = DatabaseFactory.getConnection();
			Statement statement = con.createStatement())
		{
			statement.execute("CREATE TABLE IF NOT EXISTS fake_player_memory (bot_id INT NOT NULL, player VARCHAR(35) NOT NULL, score INT NOT NULL DEFAULT 0, kills INT NOT NULL DEFAULT 0, helps INT NOT NULL DEFAULT 0, note VARCHAR(255) NOT NULL DEFAULT '', updated BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (bot_id, player))");
			try (ResultSet rset = statement.executeQuery("SELECT bot_id, player, score, kills, helps, note, updated FROM fake_player_memory"))
			{
				int count = 0;
				while (rset.next())
				{
					final Memory memory = new Memory();
					memory.score = rset.getInt("score");
					memory.kills = rset.getInt("kills");
					memory.helps = rset.getInt("helps");
					memory.note = rset.getString("note");
					memory.updated = rset.getLong("updated");
					_memories.computeIfAbsent(rset.getInt("bot_id"), key -> new ConcurrentHashMap<>()).put(rset.getString("player").toLowerCase(), memory);
					count++;
				}
				LOGGER.info(getClass().getSimpleName() + ": Loaded " + count + " memories.");
			}
		}
		catch (Exception e)
		{
			LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not initialize.", e);
		}
		
		ThreadPool.scheduleAtFixedRate(this::save, 120000, 120000);
	}
	
	public Memory get(int botId, String playerName)
	{
		final Map<String, Memory> map = _memories.get(botId);
		return (map != null) ? map.get(playerName.toLowerCase()) : null;
	}
	
	private Memory getOrCreate(int botId, String playerName)
	{
		return _memories.computeIfAbsent(botId, key -> new ConcurrentHashMap<>()).computeIfAbsent(playerName.toLowerCase(), key -> new Memory());
	}
	
	public void onKilledBy(int botId, String playerName)
	{
		if (botId <= 0)
		{
			return;
		}
		final Memory memory = getOrCreate(botId, playerName);
		memory.kills++;
		memory.score -= 3;
		memory.updated = System.currentTimeMillis();
		memory.dirty = true;
	}
	
	public void onHelpedBy(int botId, String playerName)
	{
		if (botId <= 0)
		{
			return;
		}
		final Memory memory = getOrCreate(botId, playerName);
		memory.helps++;
		memory.score += 1;
		memory.updated = System.currentTimeMillis();
		memory.dirty = true;
	}
	
	public void adjustScore(int botId, String playerName, int delta)
	{
		if (botId <= 0)
		{
			return;
		}
		final Memory memory = getOrCreate(botId, playerName);
		memory.score += delta;
		memory.updated = System.currentTimeMillis();
		memory.dirty = true;
	}
	
	public void addNote(int botId, String playerName, String note)
	{
		if (botId <= 0)
		{
			return;
		}
		final Memory memory = getOrCreate(botId, playerName);
		memory.note = note.length() > 250 ? note.substring(0, 250) : note;
		memory.updated = System.currentTimeMillis();
		memory.dirty = true;
	}
	
	/**
	 * @param botId the bot character id.
	 * @param playerName the player.
	 * @return a russian text summary of what the bot remembers about the player, or empty string.
	 */
	public String describe(int botId, String playerName)
	{
		final Memory memory = get(botId, playerName);
		if (memory == null)
		{
			return "";
		}
		
		final StringBuilder sb = new StringBuilder(160);
		if (memory.kills > 0)
		{
			sb.append("Этот игрок убивал тебя ").append(memory.kills).append(" раз - ты его помнишь и держишь обиду. ");
		}
		if (memory.helps > 0)
		{
			sb.append("Этот игрок помогал тебе в бою ").append(memory.helps).append(" раз - ты ему благодарен. ");
		}
		if (!memory.note.isEmpty())
		{
			sb.append("Из прошлого разговора: ").append(memory.note);
		}
		return sb.toString().trim();
	}
	
	private void save()
	{
		try (Connection con = DatabaseFactory.getConnection();
			PreparedStatement statement = con.prepareStatement("REPLACE INTO fake_player_memory (bot_id, player, score, kills, helps, note, updated) VALUES (?,?,?,?,?,?,?)"))
		{
			int batch = 0;
			for (Map.Entry<Integer, Map<String, Memory>> botEntry : _memories.entrySet())
			{
				for (Map.Entry<String, Memory> entry : botEntry.getValue().entrySet())
				{
					final Memory memory = entry.getValue();
					if (!memory.dirty)
					{
						continue;
					}
					memory.dirty = false;
					statement.setInt(1, botEntry.getKey());
					statement.setString(2, entry.getKey());
					statement.setInt(3, memory.score);
					statement.setInt(4, memory.kills);
					statement.setInt(5, memory.helps);
					statement.setString(6, memory.note);
					statement.setLong(7, memory.updated);
					statement.addBatch();
					batch++;
				}
			}
			if (batch > 0)
			{
				statement.executeBatch();
			}
		}
		catch (Exception e)
		{
			LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not save.", e);
		}
	}
	
	public static FakePlayerMemoryManager getInstance()
	{
		return SingletonHolder.INSTANCE;
	}
	
	private static class SingletonHolder
	{
		protected static final FakePlayerMemoryManager INSTANCE = new FakePlayerMemoryManager();
	}
}
