//
//  UsernameCheckVC.swift
//  WOKA
//
//  Created by MacBook Pro on 20/08/24.
//

import UIKit
import Alamofire

class UsernameCheckVC: UIViewController {

    var userData = [UserNameDM]()
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var nextBtn: LocalisedElementsButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupCell()
        let color1 = #colorLiteral(red: 0.144693464, green: 0.1426281333, blue: 0.6686832905, alpha: 1)
        let color2 = #colorLiteral(red: 0.6901960784, green: 0.2745098039, blue: 0.7568627451, alpha: 1)
        nextBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        nextBtn.roundCorner()
        self.title = ""
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    func setupCell(){
        tableView.register(UINib(nibName: K.CellIdentifier.Authentication.linkedChildCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.Authentication.linkedChildCell)
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    
    @IBAction func goToLoginTapped(_ sender: LocalisedElementsButton) {
        navigationController?.setNavigationBarHidden(true, animated: true)
        /*
         if user selects any user name add it to gvar
         */
        if let selectedUserName = userData.filter({$0.isSelected == true}).first?.username{
            K.GVar.selectedUsername = selectedUserName
        }
        self.navigationController?.popToViewController(of: LoginVC.self, animated: true)
    }
}

// MARK: - TableView

extension UsernameCheckVC : TableViewSRC{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.Authentication.linkedChildCell, for: indexPath) as! LinkedChildCell
        cell.setLinkedData(data: userData[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if userData[indexPath.row].isSelected == true {
           return
        }
        for i in 0..<userData.count {
            userData[i].isSelected = false
        }
        userData[indexPath.row].isSelected = true
        tableView.reloadData()
    }
}
