//
//  SerchTextDropDown.swift
//  iPOS
//
//  Created by Daniel Ciuciu on 7/28/21.
//  Copyright © 2021 BBC. All rights reserved.
//

import Foundation
import UIKit


protocol UITextFieldDropDownDelegate {
    func itemSelected(item: IDropDownItem)
}

protocol IDropDownItem{
    var itemId: String { get }
    var itemCode: String { get }
    var itemName: String { get }
}

class UITextFieldDropDown: UITextField{

    var dataList : [IDropDownItem] = [IDropDownItem]()
    var tableView: UITableView?
    
    var dropDownDelegate: UITextFieldDropDownDelegate!
    
    open override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        self.tableView?.removeFromSuperview()
    }
    
    override open func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
    }
    
    override open func layoutSubviews() {
        super.layoutSubviews()
        self.buildSearchTableView()
    }
    
    open func showItems() {
        self.buildSearchTableView()
        self.updateSearchTableView()
        self.tableView?.isHidden = false
    }
}

extension UITextFieldDropDown: UITableViewDelegate, UITableViewDataSource {
    func buildSearchTableView() {

        if let tableView = self.tableView {
            tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CustomSearchTextFieldCell")
            tableView.delegate = self
            tableView.dataSource = self
            self.window?.addSubview(tableView)

        } else {
            self.tableView = UITableView(frame: CGRect.zero)
        }
        
        self.updateSearchTableView()
    }
    
    func updateSearchTableView() {
        
        if let tableView = tableView {
            superview?.bringSubviewToFront(tableView)
            var tableHeight: CGFloat = 0
            tableHeight = tableView.contentSize.height
            
            if tableHeight < tableView.contentSize.height {
                tableHeight -= 10
            }
            
            var tableViewFrame = CGRect(x: 0, y: 0, width: frame.size.width - 4, height: tableHeight)
            tableViewFrame.origin = self.convert(tableViewFrame.origin, to: nil)
            tableViewFrame.origin.x += 2
            tableViewFrame.origin.y += frame.size.height + 2
            UIView.animate(withDuration: 0.2, animations: { [weak self] in
                self?.tableView?.frame = tableViewFrame
            })
            
            tableView.layer.masksToBounds = true
            tableView.separatorInset = UIEdgeInsets.zero
            tableView.layer.cornerRadius = 5.0
            tableView.separatorColor = UIColor.lightGray
            tableView.backgroundColor = UIColor.white.withAlphaComponent(1.00)
            tableView.layer.borderWidth = 0.5
            tableView.layer.borderColor = UIColor.black.cgColor
            
            if self.isFirstResponder {
                superview?.bringSubviewToFront(self)
            }
            
            tableView.reloadData()
        }
    }
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomSearchTextFieldCell", for: indexPath) as UITableViewCell
        cell.backgroundColor = UIColor.clear
        let item = dataList[indexPath.row]
        cell.textLabel?.attributedText = NSAttributedString.init(string: item.itemName)
        
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.endEditing(true)
        tableView.isHidden = true
        
        let item = dataList[indexPath.row]
        self.dropDownDelegate.itemSelected(item: item)
    }
}
