//
//  CustomCheckBoxViewController.swift
//  iPOS
//
//  Created by Daniel Ciuciu on 11/19/20.
//  Copyright © 2020 BBC. All rights reserved.
//

import Foundation
import UIKit

protocol CustomCheckBoxViewControllerDelegate {
    func getSelectedItems(items: [IItem])
}

protocol IItem {
    var itemId: Int { get }
    var itemCode: String { get }
    var itemName: String { get }
    var externalCode: String { get set }
    var isChecked: Bool { get set }
}

class CustomCheckBoxViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, CustomCheckBoxCellDelegate{
    
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!
    
    var items: [IItem] = [IItem]()
    var filtereditems: [IItem] = [IItem]()
    
    var black_square = "\u{25A0}"
    var white_square = "\u{25A1}"
    
    var delegate: CustomCheckBoxViewControllerDelegate!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setDelegates()
        self.createNavBarItems()
        self.initData()
    }
    
    func createNavBarItems(){
        let dismissButton = UIBarButtonItem(image: UIImage.init(named: "cancelButton.png"), style: .plain, target: self, action: #selector(self.dismissView(_:)))
        self.navigationItem.leftBarButtonItem = dismissButton
        
        let applyFiltersButton = UIBarButtonItem(image: UIImage.init(named: "checkMark.png") , style: .plain, target: self, action: #selector(self.applyFilters(_:)))
        self.navigationItem.rightBarButtonItem = applyFiltersButton
    }
    
    func setDelegates(){
        self.searchBar.delegate = self
        self.tableView.delegate = self
        self.tableView.dataSource = self
    }
    
    func initData(){
        self.filtereditems = self.items
        self.tableView.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.filtereditems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! CustomCheckBoxCell
        cell.selectionStyle = .none
        
        let item = self.filtereditems[indexPath.row]
        
        cell.delegate = self
        cell.tfCode.text = item.externalCode
        if item.isChecked{
            cell.lfTitle.text = "\(self.black_square) \(item.itemName)"
            cell.tfCode.isHidden = false
            self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
        else{
            cell.lfTitle.text = "\(self.white_square) \(item.itemName)"
            cell.tfCode.isHidden = true
            self.tableView.deselectRow(at: indexPath, animated: false)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! CustomCheckBoxCell
        cell.selectionStyle = .none

        var item = self.filtereditems[indexPath.row]
        item.isChecked = true
        cell.tfCode.isHidden = false
        cell.lfTitle.text = "\(self.black_square) \(item.itemName)"
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! CustomCheckBoxCell
        cell.selectionStyle = .none
        
        var item = self.filtereditems[indexPath.row]
        item.isChecked = false
        cell.tfCode.isHidden = true
        cell.lfTitle.text = "\(self.white_square) \(item.itemName)"
    }
    
    @objc func dismissView(_ sender: Any){
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func applyFilters(_ sender: Any){
        self.tableView.endEditing(true)
        
        var selectedItems: [IItem] = []
        self.dismiss(animated: true, completion: {
            for item in self.items{
                if item.isChecked == true{
                    selectedItems.append(item)
                }
            }
            self.delegate.getSelectedItems(items: selectedItems)
        })
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchBar.setShowsCancelButton(true, animated: true)
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        self.perform(#selector(self.filterDataSource(searchText:)), with: searchText, afterDelay: 0)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.endEditing(true)
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.text = ""
        self.searchBar.showsCancelButton = false
        self.searchBar.endEditing(true)
        self.filterDataSource(searchText: nil)
    }
    
    @objc func filterDataSource(searchText: String?){
        self.filtereditems = self.items
        if let text = searchText, text != "" {
            self.filtereditems = self.items.filter({ $0.itemName.contains(text) })
        }
        self.tableView.reloadData()
    }
    
    func didEndEditing(cell: CustomCheckBoxCell) {
        if let indexPath = self.tableView.indexPath(for: cell){
            self.filtereditems[indexPath.row].externalCode = cell.tfCode.text ?? ""
            for var item in self.items{
                if item.itemId == self.filtereditems[indexPath.row].itemId{
                    item.externalCode = self.filtereditems[indexPath.row].externalCode
                    print("External Code: \(item.externalCode)")
                }
            }
        }
    }
}
