/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.royaldev.fictitious.commands.impl

import com.google.common.collect.Sets
import org.kitteh.irc.client.library.element.User
import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent
import org.kitteh.irc.client.library.event.helper.ActorEvent
import org.royaldev.fictitious.FictitiousBot
import org.royaldev.fictitious.games.FictitiousGame
import xyz.cardstock.cardstock.commands.BaseCommand
import xyz.cardstock.cardstock.commands.CallInfo
import xyz.cardstock.cardstock.commands.Command

@Command(
    name = "stop",
    aliases = arrayOf(
        "stopgame"
    ),
    description = "Stops a game in the channel",
    usage = "<command>",
    commandType = BaseCommand.CommandType.CHANNEL
)
class StopCommand(val fictitious: FictitiousBot) : BaseCommand() {
    override fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>) {
        if (event !is ChannelMessageEvent) return
        val game = this.fictitious.gameRegistrar.find(event.channel)
        if (game == null) {
            event.actor.sendNotice("There is not a game in this channel!")
            return
        }
        val op = event.channel.getUserModes(event.actor).orElseGet { Sets.newHashSet() }.any { it.char == 'o' }
        if (!op && game.host != game.getPlayer(event.actor, false)) {
            event.actor.sendNotice("You are neither an op nor the host.")
            return
        }
        game.stop(FictitiousGame.GameEndCause.COMMAND)
    }
}
