import Foundation
import WebSocketKit

final class BiddingPlayer: CardHoldingPlayer {

    var isStillBidding = true

    var isAllowedToOfferWedding: Bool

    init(player: DealingPlayer) {
        isAllowedToOfferWedding = true
        super.init(player: player)
    }

    init(player: WeddingPlayer) {
        isStillBidding = !player.offersWedding
        isAllowedToOfferWedding = false
        super.init(player: player)
    }

    func canPlay(game: GameType) -> Bool {
        guard let suit = game.calledSuit else {
            if game == .hochzeit {
                return canOfferWedding
            }
            return true
        }
        let sorter = game.sortingType
        guard sorter.hasCardToCall(suit, in: cards) else {
            // Player needs at least one card of the called suit
            return false
        }
        let ace = Card(suit, .ass)
        return !cards.contains(ace)
    }

    override var actions: [PlayerAction] {
        guard isStillBidding else {
            return []
        }
        var actions: [PlayerAction] = isNextActor ? [.increaseOrMatchGame, .withdrawFromAuction] : []
        if canOfferWedding {
            actions.append(.offerWedding)
        }
        return actions
    }

    private var biddingState: [PlayerState] {
        isStillBidding ? [] : [.didFold]
    }
    
    override var states: [PlayerState] {
        var states = super.states
        if !isStillBidding {
            states.append(.didFold)
        } else if isNextActor {
            states.append(.mustBid)
        }
        return states
    }
}

extension BiddingPlayer {

    var canOfferWedding: Bool {
        cards.canOfferWedding
    }
}
