//
//  SetupControllers.swift
//  DevourAndDrought
//
//  Created by Micah Gomez on 10/20/21.
//

import Foundation
import UIKit

class StartController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
	func numberOfComponents(in pickerView: UIPickerView) -> Int {
		return 1
	}
	
	func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
		return 3
	}
	
	func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
		return String(row+2) + " Players"
	}
	
	@IBOutlet var playerCountPicker: UIPickerView!
	

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view.
		playerCountPicker.delegate = self
		playerCountPicker.dataSource = self
        StartBtn.titleLabel?.font = UIFont(name: "Papyrus", size: 18)!
	}
	
	override func viewDidAppear(_ animated: Bool) {
		GlobalVars.playerCount = 2
		GlobalVars.activePlayerInt = 0
		GlobalVars.currentYear = -1
		GlobalVars.players = []
		GlobalVars.currentPlayer = player()
		GlobalVars.resourceSlots = []
	}
    
    @IBOutlet var StartBtn: UIButton!

	@IBAction func StartGame(_ sender: Any) {
		GlobalVars.playerCount = playerCountPicker.selectedRow(inComponent: 0) + 2
	}
	

}

class NamesController: UIViewController {

	@IBOutlet var PlayerName: UILabel!
	
	@IBOutlet var PlayerNameField: UITextField!
	
	//var currentPlayerInt = 0
	
	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view.
        NextBtn.titleLabel?.font = UIFont(name: "Papyrus", size: 18)!
	}

	override func viewDidAppear(_ animated: Bool) {
		//currentPlayerInt = 0
		PlayerNameField.becomeFirstResponder()
	}
    
    @IBOutlet weak var NextBtn: UIButton!
    
	@IBAction func PlayerNextBtn(_ sender: Any) {
		let createNewPlayer:player = player()
		createNewPlayer.name = PlayerNameField.text ?? "Player \(GlobalVars.activePlayerInt+1)"
		GlobalVars.players.append(createNewPlayer)
		GlobalVars.activePlayerInt = GlobalVars.activePlayerInt+1
		if (GlobalVars.activePlayerInt == GlobalVars.playerCount) {
			print("all players named!")
			let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
			if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "PlayerStart") as? UIViewController {
				self.present(viewController, animated: true, completion: nil)
			}
		} else {
			PlayerName.text = "Player \(GlobalVars.activePlayerInt+1) Name:"
			PlayerNameField.text = ""
		}
	}
	
	
}

class PlayerStartController: UIViewController {
	
	@IBOutlet var playerNameLabel: UILabel!
	
	
	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view.
        
        BeginTurnBtn.titleLabel?.font = UIFont(name: "Papyrus", size: 18)!
		
		if (GlobalVars.activePlayerInt < GlobalVars.playerCount-1) {
			GlobalVars.activePlayerInt = GlobalVars.activePlayerInt + 1
			
		} else {
			GlobalVars.activePlayerInt = 0
		}
		
		print("player: \(GlobalVars.activePlayerInt)")
		
		GlobalVars.currentPlayer = GlobalVars.players[GlobalVars.activePlayerInt]
		
		
		if(GlobalVars.activePlayerInt == 0){ //NEW YEAR
			GlobalVars.newYear()
		}
		
		playerNameLabel.text = GlobalVars.currentPlayer.name
	}
	
    
    @IBOutlet weak var BeginTurnBtn: UIButton!
    
	@IBAction func BeginTurnButton(_ sender: Any) {
		
		let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
		if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "GameView") as? UIViewController {
			self.present(viewController, animated: false, completion: nil)
		}
		
	}
}

class GameEndController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
	func numberOfComponents(in pickerView: UIPickerView) -> Int {
		return GlobalVars.playerCount
	}
	
	func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
		return 8
	}
	
	func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
		var printString:String = ""
		switch(row) {
			case 0 :
				printString = GlobalVars.players[component].name
				break;
			case 1 :
				printString = "☀️ \(GlobalVars.players[component].medallions)"
				break;
			case 2 :
				printString = "🪔 \(GlobalVars.players[component].oil)"
				break;
			case 3 :
				printString = "💧 \(GlobalVars.players[component].water)"
				break;
			case 4 :
				printString = "🌾 \(GlobalVars.players[component].wheat)"
				break;
			case 5 :
				printString = "🌽 \(GlobalVars.players[component].corn)"
				break;
			case 6 :
				printString = "🐟 \(GlobalVars.players[component].fish)"
				break;
			case 7 :
				printString = "🐂 \(GlobalVars.players[component].cattle)"
				break;
			
			
			
		   /* you can have any number of case statements */
		   default : /* Optional */
			  printString = "Error!"
		}
		
		return printString
	}
	
	@IBOutlet var playerStats: UIPickerView!
	@IBOutlet var winnerLabel: UILabel!
	

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view.
		for p in GlobalVars.players{
			
			
            print("Oil Count \(p.name): \(p.oil)")
			if(p.oil >= 10){
				p.medallions = p.medallions + 1
				print("oil row complete! \(p.medallions) medals")
			}
            print("Water Count \(p.name): \(p.water)")
			if(p.water >= 10){
				p.medallions = p.medallions + 1
				print("water row complete! \(p.medallions) medals")
			}
            print("Wheat Count \(p.name): \(p.wheat)")
			if(p.wheat >= 10){
				p.medallions = p.medallions + 1
				print("wheat row complete! \(p.medallions) medals")
			}
            print("Corn Count \(p.name): \(p.corn)")
			if(p.corn >= 10){
				p.medallions = p.medallions + 1
				print("corn row complete! \(p.medallions) medals")
			}
            print("Fish Count \(p.name): \(p.fish)")
			if(p.fish >= 10){
				p.medallions = p.medallions + 1
				print("fish row complete! \(p.medallions) medals")
			}
            print("Cattle Count \(p.name): \(p.cattle)")
			if(p.cattle >= 10){
				p.medallions = p.medallions + 1
				print("cattle row complete! \(p.medallions) medals")
			}
			
			for i in 1...10 {
				if ((p.oil >= i)&&(p.water >= i)&&(p.wheat >= i)&&(p.corn >= i)&&(p.fish >= i)&&(p.cattle >= i)){
					p.medallions = p.medallions + 1
					print("column \(i) complete! \(p.medallions) medals")
				}
			}
			
			playerStats.reloadAllComponents()
			
		}
		
        
        StartBtn.titleLabel?.font = UIFont(name: "Papyrus", size: 18)!
		//let winnerPlayer = GlobalVars.players.max { a, b in a.medallions < b.medallions }
		
		var winnerPlayer = player()
		winnerPlayer.medallions = -1
		var winnerList:[player] = [winnerPlayer]
		var oldWinnerList:[player] = []
		var winnerString:String = ""
		
		for (index, value) in GlobalVars.players.enumerated() {
			if (value.medallions > winnerList[0].medallions){
				winnerList = []
				winnerList.append(value)
			} else if (value.medallions == winnerList[0].medallions){
				winnerList.append(value)
			}
		}
		if(winnerList.count > 1){
			oldWinnerList = winnerList
			winnerList = [winnerPlayer]
			for (index, value) in oldWinnerList.enumerated() {
				if (value.cattle > winnerList[0].cattle){
					winnerList = []
					winnerList.append(value)
				} else if (value.cattle == winnerList[0].cattle){
					winnerList.append(value)
				}
			}
			if(winnerList.count > 1){
				oldWinnerList = winnerList
				winnerList = [winnerPlayer]
				for (index, value) in oldWinnerList.enumerated() {
					if (value.fish > winnerList[0].fish){
						winnerList = []
						winnerList.append(value)
					} else if (value.fish == winnerList[0].fish){
						winnerList.append(value)
					}
				}
				if(winnerList.count > 1){
					oldWinnerList = winnerList
					winnerList = [winnerPlayer]
					for (index, value) in oldWinnerList.enumerated() {
						if (value.corn > winnerList[0].corn){
							winnerList = []
							winnerList.append(value)
						} else if (value.corn == winnerList[0].corn){
							winnerList.append(value)
						}
					}
					if(winnerList.count > 1){
						oldWinnerList = winnerList
						winnerList = [winnerPlayer]
						for (index, value) in oldWinnerList.enumerated() {
							if (value.wheat > winnerList[0].wheat){
								winnerList = []
								winnerList.append(value)
							} else if (value.wheat == winnerList[0].wheat){
								winnerList.append(value)
							}
						}
						if(winnerList.count > 1){
							oldWinnerList = winnerList
							winnerList = [winnerPlayer]
							for (index, value) in oldWinnerList.enumerated() {
								if (value.water > winnerList[0].water){
									winnerList = []
									winnerList.append(value)
								} else if (value.water == winnerList[0].water){
									winnerList.append(value)
								}
							}
							if(winnerList.count > 1){
								oldWinnerList = winnerList
								winnerList = [winnerPlayer]
								for (index, value) in oldWinnerList.enumerated() {
									if (value.oil > winnerList[0].oil){
										winnerList = []
										winnerList.append(value)
									} else if (value.oil == winnerList[0].oil){
										winnerList.append(value)
									}
								}
								if(winnerList.count > 1){
									print("holy shit a tie")
									winnerString = "It's a tie!"
								}
							}
						}
					}
				}
			}
		}
		
		
		if (winnerList.count == 1){
			winnerString = "\(winnerList[0].name) Wins!"
		}
		
		winnerLabel.text = winnerString
		
		playerStats.delegate = self
		playerStats.dataSource = self
	}
    
    @IBOutlet var StartBtn: UIButton!
    
    

	@IBAction func StartGame(_ sender: Any) {
		print("New game!")
		//GlobalVars.playerCount = playerCountPicker.selectedRow(inComponent: 0) + 2
	}
}


//MARK: TODO: MULTIPEER CONNECTIVITY?
//MARK: TODO: CPU PLAYERS
