<commit_before>//
//  PapyrusViewController.swift
//  Papyrus
//
//  Created by <NAME> on 12/10/2015.
//  Copyright © 2015 CJNevin. All rights reserved.
//

import UIKit
import PapyrusCore

class PapyrusViewController: UIViewController, GamePresenterDelegate {
    enum SegueId: String {
        case PreferencesSegue
        case TilePickerSegue
        case TilesRemainingSegue
    }
    
    @IBOutlet weak var gameView: GameView!
    @IBOutlet weak var submitButton: UIBarButtonItem!
    @IBOutlet weak var resetButton: UIBarButtonItem!

    let gameQueue = NSOperationQueue()
    
    let watchdog = Watchdog(threshold: 0.2)
    
    var firstRun: Bool = false
    
    var showingUnplayed: Bool = false
    var game: Game?
    var presenter = GamePresenter()
    var lastMove: Solution?
    var gameOver: Bool = true
    var dictionary: Dawg!
    var tilePickerViewController: TilePickerViewController!
    var tilesRemainingViewController: TilesRemainingViewController!
    @IBOutlet weak var tilePickerContainerView: UIView!
    @IBOutlet weak var tilesRemainingContainerView: UIView!
    @IBOutlet weak var blackoutView: UIView!
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == SegueId.TilePickerSegue.rawValue {
            tilePickerViewController = segue.destinationViewController as! TilePickerViewController
        } else if segue.identifier == SegueId.TilesRemainingSegue.rawValue {
            tilesRemainingViewController = segue.destinationViewController as! TilesRemainingViewController
            tilesRemainingViewController.completionHandler = {
                UIView.animateWithDuration(0.25) {
                    self.tilesRemainingContainerView.alpha = 0.0
                    self.blackoutView.alpha = 0.0
                }
            }
        } else if segue.identifier == SegueId.PreferencesSegue.rawValue {
            let navigationController = segue.destinationViewController as! UINavigationController
            let preferencesController = navigationController.viewControllers.first! as! PreferencesViewController
            preferencesController.saveHandler = {
                self.newGame()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        presenter.gameView = gameView
        presenter.delegate = self
        
        gameQueue.maxConcurrentOperationCount = 1

        title = "Papyrus"
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if !firstRun {
            newGame()
            
            firstRun = true
        }
    }
    
    func handleEvent(event: GameEvent) {
        NSOperationQueue.mainQueue().addOperationWithBlock {
            switch event {
            case let .Over(winner):
                self.gameOver = true
                self.title = "Game Over"
                print("Winner: \(winner)")
                if self.tilesRemainingContainerView.alpha == 1.0 {
                    self.updateShownTiles()
                }
            case .TurnStarted:
                self.resetButton.enabled = false
                self.submitButton.enabled = false
                self.title = (self.game!.player is Human ? "Human " : "Computer ") + "\(self.game!.player.score)"
            case .TurnEnded:
                self.title = (self.game!.player is Human ? "Human " : "Computer ") + "\(self.game!.player.score)"
                if self.tilesRemainingContainerView.alpha == 1.0 {
                    self.updateShownTiles()
                }
            case let .Move(solution):
                print("Played \(solution)")
                self.lastMove = solution
                self.presenter.updateGame(self.game!, move: solution)
            case .DrewTiles(_):
                print("Drew new tiles")
            case .SwappedTiles:
                print("Swapped tiles")
            }
        }
    }
    
    func newGame() {
        submitButton.enabled = false
        resetButton.enabled = false
        gameOver = false
        title = "Starting..."
        if dictionary == nil {
            gameQueue.addOperationWithBlock { [weak self] in
                self?.dictionary = Dawg.load(NSBundle.mainBundle().pathForResource("sowpods", ofType: "bin")!)!
            }
        }
        gameQueue.addOperationWithBlock { [weak self] in
            guard let strongSelf = self else { return }
            var players = [Player]()
            for _ in 0..<Preferences.sharedInstance.opponents {
                let difficulty = Preferences.sharedInstance.difficulty
                players.append(Computer(difficulty: difficulty))
            }
            //players.append(Human())
            let superScrabble = Preferences.sharedInstance.gameType == .SuperScrabble
            let board = Board(config: superScrabble ? SuperScrabbleBoardConfig() : ScrabbleBoardConfig())
            let bag = Bag(distribution: superScrabble ? SuperScrabbleDistribution() : ScrabbleDistribution())
            strongSelf.game = Game.newGame(strongSelf.dictionary, board: board, bag: bag, players: players, eventHandler: strongSelf.handleEvent)
            NSOperationQueue.mainQueue().addOperationWithBlock {
                strongSelf.title = "Started"
                strongSelf.gameQueue.addOperationWithBlock {
                    strongSelf.game?.start()
                }
            }
        }
    }
    
    // MARK: - GamePresenterDelegate
    
    func handleBlank(tileView: TileView, presenter: GamePresenter) {
        tilePickerViewController.prepareForPresentation(game!.bag.distribution)
        tilePickerViewController.completionHandler = { letter in
            tileView.tile = letter
            self.validate()
            UIView.animateWithDuration(0.25) {
                self.tilePickerContainerView.alpha = 0.0
                self.blackoutView.alpha = 0.0
            }
        }
        view.bringSubviewToFront(self.blackoutView)
        view.bringSubviewToFront(self.tilePickerContainerView)
        UIView.animateWithDuration(0.25) {
            self.blackoutView.alpha = 0.4<commit_msg>Restored human player.<commit_after>//
//  PapyrusViewController.swift
//  Papyrus
//
//  Created by <NAME> on 12/10/2015.
//  Copyright © 2015 CJNevin. All rights reserved.
//

import UIKit
import PapyrusCore

class PapyrusViewController: UIViewController, GamePresenterDelegate {
    enum SegueId: String {
        case PreferencesSegue
        case TilePickerSegue
        case TilesRemainingSegue
    }
    
    @IBOutlet weak var gameView: GameView!
    @IBOutlet weak var submitButton: UIBarButtonItem!
    @IBOutlet weak var resetButton: UIBarButtonItem!

    let gameQueue = NSOperationQueue()
    
    let watchdog = Watchdog(threshold: 0.2)
    
    var firstRun: Bool = false
    
    var showingUnplayed: Bool = false
    var game: Game?
    var presenter = GamePresenter()
    var lastMove: Solution?
    var gameOver: Bool = true
    var dictionary: Dawg!
    var tilePickerViewController: TilePickerViewController!
    var tilesRemainingViewController: TilesRemainingViewController!
    @IBOutlet weak var tilePickerContainerView: UIView!
    @IBOutlet weak var tilesRemainingContainerView: UIView!
    @IBOutlet weak var blackoutView: UIView!
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == SegueId.TilePickerSegue.rawValue {
            tilePickerViewController = segue.destinationViewController as! TilePickerViewController
        } else if segue.identifier == SegueId.TilesRemainingSegue.rawValue {
            tilesRemainingViewController = segue.destinationViewController as! TilesRemainingViewController
            tilesRemainingViewController.completionHandler = {
                UIView.animateWithDuration(0.25) {
                    self.tilesRemainingContainerView.alpha = 0.0
                    self.blackoutView.alpha = 0.0
                }
            }
        } else if segue.identifier == SegueId.PreferencesSegue.rawValue {
            let navigationController = segue.destinationViewController as! UINavigationController
            let preferencesController = navigationController.viewControllers.first! as! PreferencesViewController
            preferencesController.saveHandler = {
                self.newGame()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        presenter.gameView = gameView
        presenter.delegate = self
        
        gameQueue.maxConcurrentOperationCount = 1

        title = "Papyrus"
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if !firstRun {
            newGame()
            
            firstRun = true
        }
    }
    
    func handleEvent(event: GameEvent) {
        NSOperationQueue.mainQueue().addOperationWithBlock {
            switch event {
            case let .Over(winner):
                self.gameOver = true
                self.title = "Game Over"
                print("Winner: \(winner)")
                if self.tilesRemainingContainerView.alpha == 1.0 {
                    self.updateShownTiles()
                }
            case .TurnStarted:
                self.resetButton.enabled = false
                self.submitButton.enabled = false
                self.title = (self.game!.player is Human ? "Human " : "Computer ") + "\(self.game!.player.score)"
            case .TurnEnded:
                self.title = (self.game!.player is Human ? "Human " : "Computer ") + "\(self.game!.player.score)"
                if self.tilesRemainingContainerView.alpha == 1.0 {
                    self.updateShownTiles()
                }
            case let .Move(solution):
                print("Played \(solution)")
                self.lastMove = solution
                self.presenter.updateGame(self.game!, move: solution)
            case .DrewTiles(_):
                print("Drew new tiles")
            case .SwappedTiles:
                print("Swapped tiles")
            }
        }
    }
    
    func newGame() {
        submitButton.enabled = false
        resetButton.enabled = false
        gameOver = false
        title = "Starting..."
        if dictionary == nil {
            gameQueue.addOperationWithBlock { [weak self] in
                self?.dictionary = Dawg.load(NSBundle.mainBundle().pathForResource("sowpods", ofType: "bin")!)!
            }
        }
        gameQueue.addOperationWithBlock { [weak self] in
            guard let strongSelf = self else { return }
            var players = [Player]()
            for _ in 0..<Preferences.sharedInstance.opponents {
                let difficulty = Preferences.sharedInstance.difficulty
                players.append(Computer(difficulty: difficulty))
            }
            players.append(Human())
            let superScrabble = Preferences.sharedInstance.gameType == .SuperScrabble
            let board = Board(config: superScrabble ? SuperScrabbleBoardConfig() : ScrabbleBoardConfig())
            let bag = Bag(distribution: superScrabble ? SuperScrabbleDistribution() : ScrabbleDistribution())
            strongSelf.game = Game.newGame(strongSelf.dictionary, board: board, bag: bag, players: players, eventHandler: strongSelf.handleEvent)
            NSOperationQueue.mainQueue().addOperationWithBlock {
                strongSelf.title = "Started"
                strongSelf.gameQueue.addOperationWithBlock {
                    strongSelf.game?.start()
                }
            }
        }
    }
    
    // MARK: - GamePresenterDelegate
    
    func handleBlank(tileView: TileView, presenter: GamePresenter) {
        tilePickerViewController.prepareForPresentation(game!.bag.distribution)
        tilePickerViewController.completionHandler = { letter in
            tileView.tile = letter
            self.validate()
            UIView.animateWithDuration(0.25) {
                self.tilePickerContainerView.alpha = 0.0
                self.blackoutView.alpha = 0.0
            }
        }
        view.bringSubviewToFront(self.blackoutView)
        view.bringSubviewToFront(self.tilePickerContainerView)
        UIView.animateWithDuration(0.25) {
            self.blackoutView.alpha = 0.4
{'fraction_non_alphanumeric': 0.08285413460759698, 'fraction_numerical': 0.006317324046327043, 'mean_word_length': 2.0279548798430604, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4933882', 'n_tokens_mistral': 3380, 'n_tokens_neox': 3164, 'n_words': 653}