//
//  GifVC.swift
//  WoWonder
//
//  Created by Muhammad Haris Butt on 11/3/20.
//  Copyright © 2020 ScriptSun. All rights reserved.
//

import UIKit
import Async
import Toast_Swift

class GifVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var headerLabel: UILabel!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var searchClearButton: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    
    // MARK: - Properties
    
    private var gifArray: [GIFData] = []
    var delegate: didSelectGIFDelegate?
    var isSearch = false
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.isSearch {
            self.isSearch = false
            self.searchButton.isHidden = false
            self.headerLabel.isHidden = false
            self.searchTextField.text = ""
            self.searchTextField.resignFirstResponder()
            self.searchTextField.isHidden = true
            self.searchClearButton.isHidden = true
        } else {
            if self.navigationController != nil {
                self.navigationController?.popViewController(animated: true)
            } else {
                self.dismiss(animated: true)
            }
        }
    }
    
    // Search Button Action
    @IBAction func searchButtonAction(_ sender: UIButton) {
        self.isSearch = true
        self.searchButton.isHidden = true
        self.headerLabel.isHidden = true
        self.searchTextField.isHidden = false
        self.searchTextField.becomeFirstResponder()
    }
    
    // Search Clear Button Action
    @IBAction func searchClearButtonAction(_ sender: UIButton) {
        self.searchTextField.text = ""
        self.searchClearButton.isHidden = true
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.collectionViewSetup()
        self.textFieldSetup()
        self.fetchTrendingGIF()
    }
    
    // Collection View Setup
    func collectionViewSetup() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(resource: R.nib.gifCollectionCell), forCellWithReuseIdentifier: R.reuseIdentifier.gifCollectionCell.identifier)
    }
    
    func textFieldSetup() {
        self.searchTextField.attributedPlaceholder = NSAttributedString(
            string: "Search...",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.searchTextField.delegate = self
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension GifVC {
    
    private func fetchTrendingGIF() {
        Async.background {
            GIFManager.instance.getTrendingGIF(limit: 45, completionBlock: { (success, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.gifArray = success?.data ?? []
                            self.collectionView.reloadData()
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            })
        }
    }
    
    private func fetchSearchGIF(textForSearch: String) {
        Async.background {
            GIFManager.instance.getSearchGIF(limit: 45, search_key: textForSearch, completionBlock: { (success, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.gifArray = success?.data ?? []
                            self.collectionView.reloadData()
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: Collection View Setup
extension GifVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.gifArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.gifCollectionCell.identifier, for: indexPath) as! GifCollectionCell
        cell.bindGif(item: self.gifArray[indexPath.row], indexPath: indexPath)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.size.width / 2 - 5 , height: collectionView.frame.size.width / 2 - 5)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        self.delegate?.didSelectGIF(GIFUrl: self.gifArray[indexPath.row].images?.downsizedLarge?.url ?? "", id: self.gifArray[indexPath.row].id ?? "")
        if self.navigationController != nil {
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true)
        }
    }
    
}

// MARK: UITextFieldDelegate
extension GifVC: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        let updatedText = (currentText as NSString).replacingCharacters(in: range, with: string)
        if updatedText.count == 0 {
            self.searchClearButton.isHidden = true
        } else {
            self.searchClearButton.isHidden = false
        }
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchSearchGIF(textForSearch: currentText)
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchSearchGIF(textForSearch: currentText)
        }
    }
    
}
