//
//  AddSavedHashtagViewController.swift
//  Tusker
//
//  Created by Shadowfacts on 12/19/19.
//  Copyright © 2019 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

class AddSavedHashtagViewController: UIViewController {

    weak var mastodonController: MastodonController!
    
    var resultsController: SearchResultsViewController!
    var searchController: UISearchController!
    
    private var collectionView: UICollectionView!
    private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
    
    init(mastodonController: MastodonController) {
        self.mastodonController = mastodonController
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = NSLocalizedString("Search", comment: "search screen title")
        
        var config = UICollectionLayoutListConfiguration(appearance: .grouped)
        config.backgroundColor = .appGroupedBackground
        config.headerMode = .supplementary
        let layout = UICollectionViewCompositionalLayout.list(using: config)
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        collectionView.delegate = self
        collectionView.allowsFocus = true
        collectionView.backgroundColor = .appGroupedBackground
        view.addSubview(collectionView)
        
        let sectionHeaderCell = UICollectionView.SupplementaryRegistration<UICollectionViewListCell>(elementKind: UICollectionView.elementKindSectionHeader) { (headerView, collectionView, indexPath) in
            var config = headerView.defaultContentConfiguration()
            config.text = NSLocalizedString("Trending Hashtags", comment: "trending hashtags section title")
            headerView.contentConfiguration = config
        }
        let registration = UICollectionView.CellRegistration<TrendingHashtagCollectionViewCell, Hashtag> { cell, indexPath, hashtag in
            cell.updateUI(hashtag: hashtag)
        }
        dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { (collectionView, indexPath, item) in
            switch item {
            case let .tag(hashtag):
                return collectionView.dequeueConfiguredReusableCell(using: registration, for: indexPath, item: hashtag)
            }
        }
        dataSource.supplementaryViewProvider = { (collectionView, elementKind, indexPath) in
            if elementKind == UICollectionView.elementKindSectionHeader {
                return collectionView.dequeueConfiguredReusableSupplementary(using: sectionHeaderCell, for: indexPath)
            } else {
                return nil
            }
        }

        resultsController = HashtagSearchResultsViewController(mastodonController: mastodonController)
        resultsController.delegate = self
        resultsController.exploreNavigationController = self.navigationController!
        
        searchController = UISearchController(searchResultsController: resultsController)
        searchController.obscuresBackgroundDuringPresentation = true
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.searchResultsUpdater = resultsController
        searchController.searchBar.autocapitalizationType = .none
        searchController.searchBar.placeholder = NSLocalizedString("Search for hashtags to save", comment: "add saved hashtag search field placeholder")
        searchController.searchBar.delegate = resultsController
        searchController.searchBar.showsCancelButton = false
        
        definesPresentationContext = true
        
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed))
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let request = Client.getTrendingHashtags(limit: 10)
        mastodonController.run(request) { (response) in
            var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
            
            guard case let .success(hashtags, _) = response,
                  hashtags.count > 0 else {
                self.dataSource.apply(snapshot)
                return
            }
            
            snapshot.appendSections([.trendingTags])
            snapshot.appendItems(hashtags.map { .tag($0) })
            self.dataSource.apply(snapshot, animatingDifferences: false)
        }
    }
    
    private func selectHashtag(_ hashtag: Hashtag) {
        show(HashtagTimelineViewController(for: hashtag, mastodonController: mastodonController), sender: nil)
    }
    
    // MARK: - Interaction
    
    @objc func doneButtonPressed() {
        dismiss(animated: true)
    }

}

extension AddSavedHashtagViewController {
    enum Section {
        case trendingTags
    }
    enum Item: Hashable {
        case tag(Hashtag)
    }
}

extension AddSavedHashtagViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch dataSource.itemIdentifier(for: indexPath) {
        case nil:
            return
        case let .tag(hashtag):
            selectHashtag(hashtag)
        }
    }
}

extension AddSavedHashtagViewController: SearchResultsViewControllerDelegate {
    func selectedSearchResult(hashtag: Hashtag) {
        selectHashtag(hashtag)
    }
}
