//: Playground - noun: a place where people can play
//: deinitializer -> deinit function
import UIKit

class PlayGround {
    static var totalCoinsInPG : Int = 10_000
    
    static func distribute(numberOfCoinsRequested : Int) -> Int{
        let numOfCoins = min(totalCoinsInPG, numberOfCoinsRequested)
        totalCoinsInPG -= numOfCoins
        return numOfCoins
    }
    
    static func receive(coins : Int){
        totalCoinsInPG += coins
    }
    
    static func log(){
        print("total coins in PlayGround : \(totalCoinsInPG)")
    }
    
}

class Player {
    var coinsInAccount : Int
    var name : String
    
    init(name : String, coins : Int){
        self.name = name
        self.coinsInAccount = PlayGround.distribute(numberOfCoinsRequested: coins)
        print("\(self.name) has joined the game with \(self.coinsInAccount) coins")
        PlayGround.log()
    }
    
    func win(coins : Int){
        let winningCoins = PlayGround.distribute(numberOfCoinsRequested: coins)
        self.coinsInAccount += winningCoins
        print("\(self.name) won \(winningCoins) coins")
        PlayGround.log()
    }
    
    deinit {
        PlayGround.receive(coins: self.coinsInAccount)
        print("\(self.name) has left the game")
        PlayGround.log()
    }
}

var p1 : Player? = Player(name : "PlayerA", coins: Int(arc4random_uniform(100)))
var p2 : Player? = Player(name : "PlayerB", coins: Int(arc4random_uniform(100)))


p1?.win(coins: Int(1001 + arc4random_uniform(1000)))
p2?.win(coins: Int(2501 + arc4random_uniform(1500)))
p1 = nil
p2 = nil

p1 = Player(name: "PlayerC", coins: 2100)
p2 = Player(name: "PlayerD", coins: 3000)


