//
//  ConsoleViewController.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
import Combine

class ConsoleLibraryViewController: UIViewController {
    @IBOutlet weak var consoleItemTable: UITableView!
    @IBOutlet weak var category: UISegmentedControl!
    @IBOutlet weak var toggleWishList: UIBarButtonItem!
    
    var subsriber : Subscribers.Sink<NSSet, Never>?
    var videoGamesInLibrary : [Bool : [Game]] = [:]
    var accessoriesinLibrary : [Bool : [Accessory]] = [:]
    var showWishlist : Bool = false
    
    var console : Console? {
        didSet {
            self.title = console?.name ?? "N/A"
            
            //Remove subscription to old console object
            subsriber?.cancel()
            
            subsriber = console?.publisher(for: \.games, options: .new).sink(receiveValue: {_ in
                self.refreshConsoleLibrary()
            })
            
            refreshConsoleLibrary()
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "detail" {
            guard let indexpath = self.consoleItemTable.indexPathForSelectedRow else {
                print("ConsoleLibraryViewController::prepare::detail IndexPath for selectedRow could not be retreived")
                return
            }
            
            if let dest = segue.destination as? GameDetailController {
                dest.game = self.videoGamesInLibrary[self.showWishlist]?[indexpath.row]
            }else if let dest = segue.destination as? AccessoryDetailController {
                dest.accessory = self.accessoriesinLibrary[self.showWishlist]?[indexpath.row]
            }
        }else if (segue.identifier == "consoleEntryAdd") {
            guard let addPopup = segue.destination as? AddEntryPopUpViewController else {
                print("ConsoleLibraryViewController::prepare::consoleEntryAdd Destination is no AddEntryPopUpViewController")
                return
            }
            
            addPopup.console = self.console
            addPopup.isVideogame = self.category.selectedSegmentIndex == 0
        }
        
    }
    
    @IBAction func categoryChanged(_ sender: Any) {
        self.consoleItemTable.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if self.showWishlist {
            self.toggleWishList.tintColor = UIColor.red
        }else{
            self.toggleWishList.tintColor = UIColor.black
        }
            
        self.toggleWishList.tintColor = UIColor.black
    }
    
    func refreshConsoleLibrary() {
        let videogames = self.console?.games.map({$0 as! Game}) ?? []
        self.videoGamesInLibrary[true] = videogames.filter({$0.inWishlist})
        self.videoGamesInLibrary[false] = videogames.filter({!$0.inWishlist})
        
        let accessories = self.console?.accessories.map({$0 as! Accessory}) ?? []
        self.accessoriesinLibrary[true] = accessories.filter({$0.inWishlist})
        self.accessoriesinLibrary[false] = accessories.filter({!$0.inWishlist})
        
        consoleItemTable?.reloadData()
    }
    
    @IBAction func toggleWishlist(_ sender: Any) {
       self.showWishlist = !self.showWishlist
        
        if self.showWishlist {
            self.toggleWishList.tintColor = UIColor.red
        }else{
            self.toggleWishList.tintColor = UIColor.black
        }
        
        consoleItemTable.reloadData()
    }
}

extension ConsoleLibraryViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.category.selectedSegmentIndex == 0 {
            return self.videoGamesInLibrary[self.showWishlist]?.count ?? 0
        }else{
            return self.accessoriesinLibrary[self.showWishlist]?.count ?? 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.category.selectedSegmentIndex == 0 {
            let gameCell = tableView.dequeueReusableCell(withIdentifier: "gameCell") as! GameCell
            
            gameCell.game = self.videoGamesInLibrary[self.showWishlist]?[indexPath.row]
            
            return gameCell
        }else{
            let accessoryCell = tableView.dequeueReusableCell(withIdentifier: "accessoryCell") as! AccessoryCell
            
            
            accessoryCell.accessory = self.accessoriesinLibrary[self.showWishlist]?[indexPath.row]
            
            return accessoryCell
        }
        
    }
}


// Swipe Action - Delete / move console items from / into the library
extension ConsoleLibraryViewController: UITableViewDelegate {
    
    // Move console item to library
    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let bought  = UIContextualAction(style: .destructive, title: "") { (action, view, actionDone) in
            actionDone(true)
            if self.category.selectedSegmentIndex == 0 {
                let game = self.videoGamesInLibrary[self.showWishlist]?[indexPath.row]
                game?.inWishlist = false
            }else{
                let accessory = self.accessoriesinLibrary[self.showWishlist]?[indexPath.row]
                accessory?.inWishlist = false
            }
            
            self.refreshConsoleLibrary()
        }
        
        bought.image = #imageLiteral(resourceName: "cave")
        bought.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
        
        if (self.showWishlist) {
            return UISwipeActionsConfiguration(actions: [bought])
        }
        
        return UISwipeActionsConfiguration(actions: [])
    }
    
    // Delete console item from library
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        /*let selectedItem = self.consoleItemsToDisplay()[indexPath.row]
        let delete  = UIContextualAction(style: .destructive, title: "Delete") { (action, view, actionDone) in
            let deleteWarning = UIAlertController(  title: "Aus Zockerhöhle entfernen",
                                                    message: "Willst du '\("N/A")' wirklich aus der Zockerhöhle tragen?",
                                                    preferredStyle: .alert)
            
            deleteWarning.addAction(UIAlertAction(title: "Ja", style: .destructive, handler: { (action) in
                actionDone(true)
                
                //FlockeWS.deleteEntry(by: selectedItem.id);
                //GameCollection.shared.removeGameItem(from: self.currentConsole!, item: selectedItem)
            }))
            
            deleteWarning.addAction(UIAlertAction(title: "Nein", style: .cancel, handler: { (action) in
                actionDone(false)
            }))
            
            self.present(deleteWarning, animated: true, completion: nil)
        }*/
        
        //delete.image = #imageLiteral(resourceName: "delete")
        //delete.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
        
        return UISwipeActionsConfiguration(actions: [])//delete])
    }
}
