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

import UIKit

class AddEntryPopUpViewController: UIViewController {
    var isWishlist : Bool = false
    var isVideogame : Bool = true
    var console : Console?
    
    @IBOutlet weak var icon: UIImageView!
    @IBOutlet weak var category: UISegmentedControl!
    @IBOutlet weak var wishlistIcon: UIImageView!
    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var addButton: UIButtonX!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.category.selectedSegmentIndex = 0
        
        if (!self.isVideogame && !self.isWishlist) {
            self.category.selectedSegmentIndex = 1
        }
        
        self.wishlistIcon.isHidden = !self.isWishlist
        
        self.icon.image = self.console?.logo?.image
        
        //If the name is not filled the add Button should be disabled
        addButton.isEnabled = name.text != ""
    }
    
    @IBAction func nameChanged(_ sender: Any) {
        addButton.isEnabled = name.text != ""
    }
    
    @IBAction func add(_ sender: Any) {
        self.isVideogame = self.category.selectedSegmentIndex == 0
        
        guard let name = self.name.text else {
            print("ERROR AddEntryPopoUpViewController::Add; Game name is empty")
            return
        }
        
        if self.isVideogame {
            let game = Game(entity: Game.entity(), insertInto: CDManager.shared.viewContext)
            game.name = name
            game.console = console
            
            print("Added Game '\(game.name)'")
        }else{
            let accessory = Accessory(entity: Accessory.entity(), insertInto: CDManager.shared.viewContext)
            accessory.name = name
            accessory.console = console
            
            print("Added Accessory '\(accessory.name)'")
        }
        
        self.dismiss(animated: true)
    }
    
    @IBAction func cancel(_ sender: Any) {
        self.dismiss(animated: true)
    }
}
