//
//  ViewController.swift
//  DevourAndDrought
//
//  Created by Micah Gomez on 10/17/21.
//

extension UIImage {
    func rotate(radians: Float) -> UIImage? {
        var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
        // Trim off the extremely small float value to prevent core graphics from rounding it up
        newSize.width = floor(newSize.width)
        newSize.height = floor(newSize.height)

        UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
        let context = UIGraphicsGetCurrentContext()!

        // Move origin to middle
        context.translateBy(x: newSize.width/2, y: newSize.height/2)
        // Rotate around middle
        context.rotate(by: CGFloat(radians))
        // Draw the image at its center
        self.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height))

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }
}

extension UIImage {
    func cropsToSquare() -> UIImage? {
        if let image = self.cgImage {
            let refWidth = CGFloat((image.width))
            let refHeight = CGFloat((image.height))
            let cropSize = refWidth > refHeight ? refHeight*0.4 : refWidth*0.4
            
            let x = (refWidth - cropSize) / 2.0
            let y = (refHeight - cropSize) / 2.0
            
            let cropRect = CGRect(x: x, y: y, width: cropSize, height: cropSize)
            let imageRef = image.cropping(to: cropRect)
            let cropped = UIImage(cgImage: imageRef!, scale: 0.0, orientation: self.imageOrientation)
            return cropped
        }
        return nil
    }
}

func deg2rad(_ number: Double) -> Double {
    return number * .pi / 180
}

import UIKit

class PlayerBoardController: UIViewController {
	
	@IBOutlet var playerNameLabel: UILabel!
	
	@IBOutlet var playerOilCount: UILabel!
	@IBOutlet var playerWaterCount: UILabel!
	@IBOutlet var playerWheatCount: UILabel!
	@IBOutlet var playerCornCount: UILabel!
	@IBOutlet var playerFishCount: UILabel!
	@IBOutlet var playerCattleCount: UILabel!
	@IBOutlet var medallionCount: UILabel!
    @IBOutlet weak var EndTurnBtn: UIButton!
    

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view.
		EndTurnBtn.titleLabel?.font = UIFont(name: "Papyrus", size: 18)!
	}
	
	override func viewWillAppear(_ animated: Bool) {
		
		playerNameLabel.text = GlobalVars.currentPlayer.name
		playerOilCount.text = String("")
		playerWaterCount.text = String("")
		playerWheatCount.text = String("")
		playerCornCount.text = String("")
		playerFishCount.text = String("")
		playerCattleCount.text = String("")
		medallionCount.text = String("")

		for _ in 0...GlobalVars.currentPlayer.oil {
			playerOilCount.text?.append("🪔")
		}
		for _ in 0...GlobalVars.currentPlayer.water {
			playerWaterCount.text?.append("💧")
		}
		for _ in 0...GlobalVars.currentPlayer.wheat {
			playerWheatCount.text?.append("🌾")
		}
		for _ in 0...GlobalVars.currentPlayer.corn {
			playerCornCount.text?.append("🌽")
		}
		for _ in 0...GlobalVars.currentPlayer.fish {
			playerFishCount.text?.append("🐟")
		}
		for _ in 0...GlobalVars.currentPlayer.cattle {
			playerCattleCount.text?.append("🐂")
		}
		
		playerOilCount.text?.remove(at: (playerOilCount.text?.firstIndex(of: "🪔"))!)
		playerWaterCount.text?.remove(at: (playerWaterCount.text?.firstIndex(of: "💧"))!)
		playerWheatCount.text?.remove(at: (playerWheatCount.text?.firstIndex(of: "🌾"))!)
		playerCornCount.text?.remove(at: (playerCornCount.text?.firstIndex(of: "🌽"))!)
		playerFishCount.text?.remove(at: (playerFishCount.text?.firstIndex(of: "🐟"))!)
		playerCattleCount.text?.remove(at: (playerCattleCount.text?.firstIndex(of: "🐂"))!)
		
		if(GlobalVars.currentPlayer.oil >= 10){
			playerOilCount.text?.append("☀️")
		}
		if(GlobalVars.currentPlayer.water >= 10){
			   playerWaterCount.text?.append("☀️")
		}
		if(GlobalVars.currentPlayer.wheat >= 10){
			playerWheatCount.text?.append("☀️")
		}
		if(GlobalVars.currentPlayer.corn >= 10){
			   playerCornCount.text?.append("☀️")
		}
		if(GlobalVars.currentPlayer.fish >= 10){
			   playerFishCount.text?.append("☀️")
		}
		if(GlobalVars.currentPlayer.cattle >= 10){
			   playerCattleCount.text?.append("☀️")
		}
		
		for i in 0...9 {
			if ((GlobalVars.currentPlayer.oil >= i)&&(GlobalVars.currentPlayer.water >= i)&&(GlobalVars.currentPlayer.wheat >= i)&&(GlobalVars.currentPlayer.corn >= i)&&(GlobalVars.currentPlayer.fish >= i)&&(GlobalVars.currentPlayer.cattle >= i)){
				medallionCount.text?.append("☀️")
			}
		}
		medallionCount.text?.remove(at: (medallionCount.text?.firstIndex(of: "☀️"))!)
		
	}

	@IBAction func EndTurn(_ sender: Any) {
	
		print("year: \(GlobalVars.currentYear)")
		print("playerCount: \(GlobalVars.playerCount)")
		print("activePlayer: \(GlobalVars.activePlayerInt)")
		
		GlobalVars.players[GlobalVars.activePlayerInt] = GlobalVars.currentPlayer
		
        let confirmAlert = UIAlertController(title: "End Turn?", message: "To end your turn, press Ok and pass the device to the next player.", preferredStyle: UIAlertController.Style.alert)

        confirmAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
              
            if((GlobalVars.currentYear == 6) && ((GlobalVars.activePlayerInt+1) == GlobalVars.playerCount)){
                let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
                if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "GameEndScreen") as? UIViewController {
                    self.present(viewController, animated: true, completion: nil)
                }
            } else {
               
                let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
                if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "PlayerStart") as? UIViewController {
                    self.present(viewController, animated: true, completion: nil)
               }
            }
            
        }))

        confirmAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
              print("Handle Cancel Logic here")
        }))

        present(confirmAlert, animated: true, completion: nil)
        
		
		
		
	}
	

}

class GameBoardController: UIViewController {
	
	@IBOutlet var PlayerNameLabel: UILabel!
	@IBOutlet var LbrPointsLbl: UILabel!
    @IBOutlet var RsrcPointsLbl: UILabel!
    
	
	@IBOutlet var ResourceSlot1: UIButton!
	@IBOutlet var ResourceSlot2: UIButton!
	@IBOutlet var ResourceSlot3: UIButton!
	@IBOutlet var ResourceSlot4: UIButton!
	@IBOutlet var ResourceSlot5: UIButton!
	@IBOutlet var ResourceSlot6: UIButton!
	@IBOutlet var ResourceSlot7: UIButton!
	
	@IBOutlet var AllResourceSlots : [UIButton]!
	
	//let buttonList:[UIButton] = [ResourceSlot1,ResourceSlot2,ResourceSlot3,ResourceSlot4,ResourceSlot5,ResourceSlot6,ResourceSlot7]
	
	var resourceList:[resource] = []
	//var resourceSlots:[resource] = []
	

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view.
		
		let resourceNames:[String] = ["Oil\n🪔","Water\n💧","Wheat\n🌾","Corn\n🌽","Fish\n🐟","Cattle\n🐂"]
		let resourceCosts:[Int] = [1,2,3,4,5,6]
		
		for i in 0...5 {
			let createResource = resource()
			createResource.name = resourceNames[i]
			createResource.cost = resourceCosts[i]
			resourceList.append(createResource)
		}
		
		
		if (GlobalVars.resourceSlots.count == 0){
			for y in 0...6 {
				let createSlot = resourceList.randomElement()
				print(createSlot?.name)
				print(createSlot?.cost)
				/*if(y == GlobalVars.currentYear){
					createSlot?.cost = createSlot!.cost - 1
				}*/
				GlobalVars.resourceSlots.append(createSlot!)
			}
		}
		
		//MARK: TODO: add cost after discount has been applied
		for (index,item) in AllResourceSlots.enumerated() {
			print(index,item)
			//item.setTitle("\(GlobalVars.resourceSlots[index].name)", for: .normal)
			//item.setTitle("\(GlobalVars.resourceSlots[index].name)\n/*\(GlobalVars.resourceSlots[index].cost)", for: .normal)
			item.titleLabel?.numberOfLines = 0
			item.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
			item.titleLabel?.textAlignment = NSTextAlignment.center
			//item.layer.shadowPath = UIBezierPath(rect: item.layer.bounds).cgPath
			/*item.layer.shadowColor = UIColor.black.cgColor
			item.layer.shadowRadius = 13.0
			item.layer.shadowOpacity = 0*/
			if(GlobalVars.currentYear == index){
				item.layer.borderColor = UIColor(red: 0.20, green: 0.47, blue: 0.20, alpha: 1.00).cgColor
				item.layer.borderWidth = 2
			}
            let goldimage = UIImage(named: "gold_bg")
            let randomInt = Int.random(in: 1...360)
            print(randomInt)
            var bgimage = goldimage?.rotate(radians: Float(deg2rad(Double(randomInt))))
            bgimage = bgimage?.cropsToSquare()
            
            item.setBackgroundImage(bgimage, for: .normal)
            
            /*let shadowLayer = CALayer()
            shadowLayer.masksToBounds = false
            shadowLayer.shadowColor = shadowColor?.cgColor
            shadowLayer.shadowOffset = shadowOffset
            shadowLayer.shadowOpacity = shadowOpacity
            shadowLayer.shadowRadius = shadowRadius
            shadowLayer.shadowPath = UIBezierPath(rect: rect).cgPath
            layer.insertSublayer(shadowLayer, at: 0)
            self.shadowLayer = shadowLayer*/
            
			if(GlobalVars.resourceSlots[GlobalVars.currentYear].name == GlobalVars.resourceSlots[index].name){
				item.setTitle("\(GlobalVars.resourceSlots[index].name)\n\((GlobalVars.resourceSlots[index].cost - 1))", for: .normal)
			} else {
				item.setTitle("\(GlobalVars.resourceSlots[index].name)\n\(GlobalVars.resourceSlots[index].cost)", for: .normal)
			}
		}
	}
	
	override func viewWillAppear(_ animated: Bool) {
		PlayerNameLabel.text = GlobalVars.players[GlobalVars.activePlayerInt].name
		LbrPointsLbl.text = "Labor Points: \(GlobalVars.currentPlayer.laborpoints)"
	}
/*
	@IBAction func ResourceSlotOne(_ sender: Any) {
		ResourceSlot1.setTitle("\(resourceSlots[0].name)\n\(resourceSlots[0].cost)", for: .normal)
	}
	
	@IBAction func ResourceSlotTwo(_ sender: Any) {
		ResourceSlot2.setTitle("\(resourceSlots[1].name)\n\(resourceSlots[1].cost)", for: .normal)
	}
	
	@IBAction func ResourceSlotThree(_ sender: Any) {
		ResourceSlot3.setTitle("\(resourceSlots[2].name)\n\(resourceSlots[2].cost)", for: .normal)
	}
	
	@IBAction func ResourceSlotFour(_ sender: Any) {
		ResourceSlot4.setTitle("\(resourceSlots[3].name)\n\(resourceSlots[3].cost)", for: .normal)
	}
	
	@IBAction func ResourceSlotFive(_ sender: Any) {
		ResourceSlot5.setTitle("\(resourceSlots[4].name)\n\(resourceSlots[4].cost)", for: .normal)
	}
	
	@IBAction func ResourceSlotSix(_ sender: Any) {
		ResourceSlot6.setTitle("\(resourceSlots[5].name)\n\(resourceSlots[5].cost)", for: .normal)
	}
	
	@IBAction func ResourceSlotSeven(_ sender: UIButton) {
		ResourceSlot7.setTitle("\(resourceSlots[6].name)\n\(resourceSlots[6].cost)", for: .normal)
	}
	*/
	
	@IBAction func boxTouched(_ sender: UIButton) {
		let index = AllResourceSlots.index(of: sender)!
		if !sender.isSelected{
            var resourceCount = 0
			for (i, item) in GlobalVars.resourceSlots.enumerated() {
				//print(i,item)
				
				AllResourceSlots[i].isSelected = false
				//AllResourceSlots[i].layer.shadowOpacity = 0
                UIView.animate(withDuration: 0.1, animations: {
                    self.AllResourceSlots[i].transform = CGAffineTransform(translationX: 0, y: 0)
                })
				if item.name == GlobalVars.resourceSlots[index].name {
					AllResourceSlots[i].isSelected = true
                    UIView.animate(withDuration: 0.1, animations: {
                        self.AllResourceSlots[i].transform = CGAffineTransform(translationX: 0, y: -20)
                    })
					//AllResourceSlots[i].layer.shadowOpacity = 0.75
                    resourceCount += 1
				}
			}
            
            var resourceTotal = 0
            switch(GlobalVars.resourceSlots[index].name) {
                case "Oil\n🪔" :
                    if ((GlobalVars.currentPlayer.oil + resourceCount) > 10){
                        resourceTotal = 10
                    } else {
                        resourceTotal = GlobalVars.currentPlayer.oil + resourceCount
                    }
                    RsrcPointsLbl.text = "Oil 🪔: \(GlobalVars.currentPlayer.oil) > \(resourceTotal)"
                    break;
                case "Water\n💧" :
                    if ((GlobalVars.currentPlayer.water + resourceCount) > 10){
                        resourceTotal = 10
                    } else {
                        resourceTotal = GlobalVars.currentPlayer.water + resourceCount
                    }
                    RsrcPointsLbl.text = "Water 💧: \(GlobalVars.currentPlayer.water) > \(resourceTotal)"
                    break;
                case "Wheat\n🌾" :
                    if ((GlobalVars.currentPlayer.wheat + resourceCount) > 10){
                        resourceTotal = 10
                    } else {
                        resourceTotal = GlobalVars.currentPlayer.wheat + resourceCount
                    }
                    RsrcPointsLbl.text = "Wheat 🌾: \(GlobalVars.currentPlayer.wheat) > \(resourceTotal)"
                    break;
                case "Corn\n🌽" :
                    if ((GlobalVars.currentPlayer.corn + resourceCount) > 10){
                        resourceTotal = 10
                    } else {
                        resourceTotal = GlobalVars.currentPlayer.corn + resourceCount
                    }
                    RsrcPointsLbl.text = "Corn 🌽: \(GlobalVars.currentPlayer.corn) > \(resourceTotal)"
                    break;
                case "Fish\n🐟" :
                    if ((GlobalVars.currentPlayer.fish + resourceCount) > 10){
                        resourceTotal = 10
                    } else {
                        resourceTotal = GlobalVars.currentPlayer.fish + resourceCount
                    }
                    RsrcPointsLbl.text = "Fish 🐟: \(GlobalVars.currentPlayer.fish) > \(resourceTotal)"
                    break;
                case "Cattle\n🐂" :
                    if ((GlobalVars.currentPlayer.cattle + resourceCount) > 10){
                        resourceTotal = 10
                    } else {
                        resourceTotal = GlobalVars.currentPlayer.cattle + resourceCount
                    }
                    RsrcPointsLbl.text = "Cattle 🐂: \(GlobalVars.currentPlayer.cattle) > \(resourceTotal)"
                    break;
              
               /* you can have any number of case statements */
               default : /* Optional */
                  print("uh oh!")
            }
            if(GlobalVars.resourceSlots[GlobalVars.currentYear].name == GlobalVars.resourceSlots[index].name){
                LbrPointsLbl.text = "Labor Points: \(GlobalVars.currentPlayer.laborpoints) > \(GlobalVars.currentPlayer.laborpoints - (GlobalVars.resourceSlots[index].cost) + 1)"
                if (GlobalVars.currentPlayer.laborpoints - (GlobalVars.resourceSlots[index].cost) + 1) < 0 {
                    LbrPointsLbl.textColor = UIColor.red
                } else {
                    LbrPointsLbl.textColor = UIColor(red: 0.49, green: 0.42, blue: 0.31, alpha: 1.00)
                }
            } else {
                LbrPointsLbl.text = "Labor Points: \(GlobalVars.currentPlayer.laborpoints) > \(GlobalVars.currentPlayer.laborpoints - GlobalVars.resourceSlots[index].cost)"
                if (GlobalVars.currentPlayer.laborpoints - (GlobalVars.resourceSlots[index].cost)) < 0 {
                    LbrPointsLbl.textColor = UIColor.red
                } else {
                    LbrPointsLbl.textColor = UIColor(red: 0.49, green: 0.42, blue: 0.31, alpha: 1.00)
                }
            }
		} else {
			if(AllResourceSlots[GlobalVars.currentYear].isSelected){
				if((GlobalVars.currentPlayer.laborpoints - (GlobalVars.resourceSlots[index].cost - 1)) >= 0){
					GlobalVars.currentPlayer.laborpoints = GlobalVars.currentPlayer.laborpoints - (GlobalVars.resourceSlots[index].cost - 1)
				} else {
					return
				}
			} else {
				if((GlobalVars.currentPlayer.laborpoints - GlobalVars.resourceSlots[index].cost) >= 0){
					GlobalVars.currentPlayer.laborpoints = GlobalVars.currentPlayer.laborpoints - GlobalVars.resourceSlots[index].cost
				} else {
					return
				}
				
			}
			
			
			print("PURCHASED!!!")
			for (i, item) in GlobalVars.resourceSlots.enumerated() {
				if AllResourceSlots[i].isSelected {
					addToInventory(name: GlobalVars.resourceSlots[i].name)
					print("resource name: \(GlobalVars.resourceSlots[i].name)")
					GlobalVars.resourceSlots[i] = resourceList.randomElement()!
					/*AllResourceSlots[i].setTitle("\(GlobalVars.resourceSlots[i].name)\n\(GlobalVars.resourceSlots[i].cost)", for: .normal)
					if(GlobalVars.resourceSlots[GlobalVars.currentYear].name == GlobalVars.resourceSlots[i].name){
						AllResourceSlots[i].setTitle("\(GlobalVars.resourceSlots[i].name)\n\((GlobalVars.resourceSlots[i].cost - 1))", for: .normal)
					} else {
						AllResourceSlots[i].setTitle("\(GlobalVars.resourceSlots[i].name)\n\(GlobalVars.resourceSlots[i].cost)", for: .normal)
					}*/
					for (index,ii) in AllResourceSlots.enumerated() {
                        UIView.animate(withDuration: 0.25, animations: {
                            self.AllResourceSlots[i].transform = CGAffineTransform(scaleX: -1, y: 1)
                        })
						if(GlobalVars.resourceSlots[GlobalVars.currentYear].name == GlobalVars.resourceSlots[index].name){
							ii.setTitle("\(GlobalVars.resourceSlots[index].name)\n\((GlobalVars.resourceSlots[index].cost - 1))", for: .normal)
						} else {
							ii.setTitle("\(GlobalVars.resourceSlots[index].name)\n\(GlobalVars.resourceSlots[index].cost)", for: .normal)
						}
                        UIView.animate(withDuration: 0.25, animations: {
                            self.AllResourceSlots[i].transform = CGAffineTransform(scaleX: 1, y: 1)
                        })
					}
                   
				}
				AllResourceSlots[i].isSelected = false
				AllResourceSlots[i].layer.shadowOpacity = 0
				LbrPointsLbl.text = "Labor Points: \(GlobalVars.currentPlayer.laborpoints)"
                RsrcPointsLbl.text = ""
                
			}
		}
		print(GlobalVars.currentPlayer.oil,GlobalVars.currentPlayer.water,GlobalVars.currentPlayer.wheat,GlobalVars.currentPlayer.corn,GlobalVars.currentPlayer.fish,GlobalVars.currentPlayer.cattle)
		
	}
	
	//MARK: TODO: DONT ALLOW PURCHASE IF NOT ENOUGH LABOR POINTS
	func addToInventory(name: String){
		print("adding!")
		switch(name) {
			case "Oil\n🪔" :
				GlobalVars.currentPlayer.oil = GlobalVars.currentPlayer.oil + 1
				if(GlobalVars.currentPlayer.oil > 10){
					GlobalVars.currentPlayer.oil = 10
				}
				break;
			case "Water\n💧" :
				GlobalVars.currentPlayer.water = GlobalVars.currentPlayer.water + 1
				if(GlobalVars.currentPlayer.water > 10){
					GlobalVars.currentPlayer.water = 10
				}
				break;
			case "Wheat\n🌾" :
				GlobalVars.currentPlayer.wheat = GlobalVars.currentPlayer.wheat + 1
				if(GlobalVars.currentPlayer.wheat > 10){
					GlobalVars.currentPlayer.wheat = 10
				}
				break;
			case "Corn\n🌽" :
				GlobalVars.currentPlayer.corn = GlobalVars.currentPlayer.corn + 1
				if(GlobalVars.currentPlayer.corn > 10){
					GlobalVars.currentPlayer.corn = 10
				}
				break;
			case "Fish\n🐟" :
				GlobalVars.currentPlayer.fish = GlobalVars.currentPlayer.fish + 1
				if(GlobalVars.currentPlayer.fish > 10){
					GlobalVars.currentPlayer.fish = 10
				}
				break;
			case "Cattle\n🐂" :
				GlobalVars.currentPlayer.cattle = GlobalVars.currentPlayer.cattle + 1
				if(GlobalVars.currentPlayer.cattle > 10){
					GlobalVars.currentPlayer.cattle = 10
				}
				break;
		  
		   /* you can have any number of case statements */
		   default : /* Optional */
			  print("uh oh!")
		}
	}
	
}
