//
//  UIConsoleTableViewController.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 12.09.18.
//  Copyright © 2018 Julian-Steffen Müller. All rights reserved.
//

import UIKit
import CoreData

class AllConsolesViewController: UIViewController, NSFetchedResultsControllerDelegate {
    @IBOutlet weak var consolesTable: UITableView!
    @IBOutlet weak var manufacturer: UILabel!
    @IBOutlet weak var consoleLogo: UIImageView!
    
    lazy var fetchResultsController : NSFetchedResultsController<Console> = {
        let consolesFetch : NSFetchRequest<Console> = Console.fetchRequest()
        
        consolesFetch.sortDescriptors = [NSSortDescriptor(key: "manufacturer", ascending: true), NSSortDescriptor(key: "generation", ascending: true), NSSortDescriptor(key: "name", ascending: true)]
        
        var consolesfetchRC =  NSFetchedResultsController(fetchRequest: consolesFetch, managedObjectContext: CDManager.shared.viewContext, sectionNameKeyPath: nil, cacheName: nil)
        
        consolesfetchRC.delegate = self
        
        return consolesfetchRC

    }()
    
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        print("AllConsolesViewController::controllerDidChangeContent")
        self.consolesTable.reloadData()
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "consoleDetail" && sender! is ConsoleCell) {
            guard let consoleVC = segue.destination as? ConsoleLibraryViewController else {
                return
            }
            guard let consoleCell = sender as? ConsoleCell else {
                return
            }
            
            consoleVC.console = consoleCell.console
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        FlockeWS.fetchEntries(for: GameCollection.consoleID)
        do {
            try fetchResultsController.performFetch()
        }catch{
            print("AllConsolesViewController::viewDidLoad: Fetch not possible");
        }
    }
}
extension AllConsolesViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        guard let sections = fetchResultsController.sections else { return 0 }
        
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let sections = fetchResultsController.sections else { return 0 }
        
        return sections[section].numberOfObjects
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = (tableView.dequeueReusableCell(withIdentifier: "ConsoleCell", for: indexPath)) as! ConsoleCell

        cell.console = fetchResultsController.object(at: indexPath)

        return cell
    }
}
