//
//  GameScene.swift
//  HomerSampleApp
//
//  Created by Shawn Campbell on 3/15/19.
//  Copyright © 2019 Shawn Campbell. All rights reserved.
//
import SpriteKit
import GameplayKit

class GameScene : SKScene {
    public var gridSize = "4x4"
    let values = Bundle.main.contents(plist: "Info.plist")
    var game : Game? = nil
    let button = SKSpriteNode(imageNamed: "backNavButton")
    var firstCardShowing : SKSpriteNode?
    var secondCardShowing : SKSpriteNode?
    let cardHeight : Float = 200.0
    let cardWidth : Float = 125.0
    private var gameLabel : SKLabelNode?
    
    
    override func didMove(to view: SKView) {
        self.gameLabel = self.childNode(withName: "//statusLabel") as? SKLabelNode
        if let gl = self.gameLabel {
            gl.alpha = 0.0
            gl.run(SKAction.fadeIn(withDuration: 2.0)) {
                gl.run(SKAction.fadeOut(withDuration: 2.0))
            }
            
        }
        button.position.x = -self.size.width/3
        button.position.y = self.size.height/2.5
        button.name = "backButton"
        self.addChild(button)
        switch gridSize {
        case "4x4":
            game = Game(gameState: GameState.readyToPlay, playingFieldConfig: GameField.cards4xrows4)
        case "3x4":
            game = Game(gameState: GameState.readyToPlay, playingFieldConfig: GameField.cards3xrows4)
        case "4x5":
            game = Game(gameState: GameState.readyToPlay, playingFieldConfig: GameField.cards4xrows5)
        case "5x2":
            game = Game(gameState: GameState.readyToPlay, playingFieldConfig: GameField.cards5xrows2)
        default:
            game = Game(gameState: GameState.readyToPlay, playingFieldConfig: GameField.cards4xrows4)
        }
        let columns = game?.columns
        let rows = game?.rows
        for i in 0...(rows! - 1) {
           
            for j in 0...(columns! - 1) {
                // Grab the middle of the scene (and screen) and start in the upper left hand
                // layout the playing field left to right dropping down for each row.
                let posX = self.frame.midX + 300 - CGFloat(Float(i) * (cardHeight + 2))
                let posY = self.frame.midY - 300 + CGFloat(Float(j) * (cardWidth + 2))
                if let pf = game?.playingField {
                    pf[i][j].cardBack.size.width = CGFloat(cardWidth)
                    pf[i][j].cardBack.size.height = CGFloat(cardHeight)
                    pf[i][j].cardBack.position.x = CGFloat(posY)
                    pf[i][j].cardBack.position.y = CGFloat(posX)
                    pf[i][j].cardBack.anchorPoint = CGPoint(x: 0, y: 0)
                    pf[i][j].cardBack.zPosition = 2
                    self.addChild(pf[i][j].cardBack)
                    pf[i][j].cardFront.size.width = CGFloat(cardWidth)
                    pf[i][j].cardFront.size.height = CGFloat(cardHeight)
                    pf[i][j].cardFront.position.x = CGFloat(posY)
                    pf[i][j].cardFront.position.y = CGFloat(posX)
                    pf[i][j].cardFront.zPosition = 1
                    pf[i][j].cardFront.anchorPoint = CGPoint(x: 0, y: 0)
                    self.addChild(pf[i][j].cardFront)
                }
                
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        let location = touch?.location(in: self)
        if let node = self.atPoint(location!) as? SKSpriteNode {
        
            if node.name == "backButton" {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: values["back to lobby key"] as! String), object: "lobby")
            } else if node.name == "cardBack" {
                node.zPosition = 0
                if let pf = game?.playingField {
                    for r in pf {
                        for c in r {
                            if c.cardBack == node {
                                if firstCardShowing == nil {
                                    firstCardShowing = c.cardFront
                                } else {
                                    secondCardShowing = c.cardFront
                                }
                            }
                        }
                    }
                }
                if firstCardShowing != nil && secondCardShowing != nil {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.checkForMatch()
                        })
                    
                }
            }
        }
        
    }
    
    func resetField() {
        for i in (game?.playingField)! {
            for j in i {
                if j.cardFront.zPosition == 1 && j.cardBack.zPosition == 0 {
                    j.cardBack.zPosition = 2
                }
            }
        }
        firstCardShowing = nil
        secondCardShowing = nil
    }
    
    func checkForMatch() {
        if let f = firstCardShowing, let s = secondCardShowing {
            if f.name == s.name {
                f.zPosition = 3
                s.zPosition = 3
                if let l = self.gameLabel {
                    l.text = "Match!"
                    l.alpha = 0.0
                    l.run(SKAction.fadeIn(withDuration: 1.5)) {
                        l.run(SKAction.fadeOut(withDuration: 1.5))
                    }
                    
                }
            } else {
                if let l = self.gameLabel {
                    l.text = "Incorrect Match!"
                    l.alpha = 0.0
                    l.run(SKAction.fadeIn(withDuration: 1.5)) {
                        l.run(SKAction.fadeOut(withDuration: 1.5))
                    }
                    
                }
            }
        }
        resetField()
    }
}
