/*
 * This file is part of CraftoPlugin, licensed under the MIT License (MIT).
 *
 * Copyright (c) 2019 CraftolutionDE <https://craftolution.de>
 *
 * 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.
 *
 * Website: https://craftolution.de/
 * Contact: support@craftolution.de
 */
package de.craftolution.craftoplugin.module.protection.utils;

import com.jerolba.bikey.BikeyMap;
import com.jerolba.bikey.TableBikeyMap;
import de.craftolution.craftoplugin.module.protection.blocks.BlockProt;
import de.craftolution.craftoplugin.module.protection.entities.EntityProt;
import de.craftolution.craftoplugin.service.messenger.Messenger;
import de.craftolution.craftoplugin.service.module.Component;
import de.craftolution.craftoplugin.service.playerstorage.StoredPlayer;
import org.bukkit.entity.Player;

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;

public class ProtInformer extends Component {

	private BikeyMap<UUID, InformReason, Instant> informMap = new TableBikeyMap<>();

	@Override
	protected void onDisable() { informMap.clear(); }

	public void inform(Player player, EntityProt prot, InformReason reason) {
		String ownerName = StoredPlayer.get(prot.getOwnerId()).map(StoredPlayer::getName).orElse("Unbekannt");
		inform(player, ownerName, reason);
	}

	public void inform(Player player, BlockProt prot, InformReason reason) {
		String ownerName = StoredPlayer.get(prot.getOwnerId()).map(StoredPlayer::getName).orElse("Unbekannt");
		inform(player, ownerName, reason);
	}

	private void inform(Player player, String ownerName, InformReason reason) {
		informMap.putIfAbsent(player.getUniqueId(), reason, Instant.MIN);

		Instant lastInform = informMap.get(player.getUniqueId(), reason);

		if (Duration.between(Instant.now(), lastInform).abs().getSeconds() > 5) {
			Messenger.sendFailure(player, reason.getMessage(), ownerName);

			informMap.put(player.getUniqueId(), reason, Instant.now());
		}
	}

}
