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

import UIKit

class FindInstanceViewController: InstanceSelectorTableViewController {

    weak var parentMastodonController: MastodonController?
    
    var instanceTimelineDelegate: InstanceTimelineViewControllerDelegate?
    
    init(parentMastodonController: MastodonController) {
        self.parentMastodonController = parentMastodonController
        
        super.init()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        delegate = self
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed))
    }

    // MARK: - Interaction
    
    @objc func cancelButtonPressed() {
        // when the search controller is active, dismiss exits it rather than dismissing ourself, so we have to dismiss twice
        if searchController.isActive {
            dismiss(animated: false) {
                self.dismiss(animated: true)
            }
        } else {
            dismiss(animated: true)
        }
    }

}

extension FindInstanceViewController: InstanceSelectorTableViewControllerDelegate {
    func didSelectInstance(url: URL) {
        let instanceTimelineController = InstanceTimelineViewController(for: url, parentMastodonController: parentMastodonController!)
        instanceTimelineController.instanceTimelineDelegate = instanceTimelineDelegate
        instanceTimelineController.browsingEnabled = false
        show(instanceTimelineController, sender: self)
    }
}
