//
//  AddInstancePinnedTimelineView.swift
//  Tusker
//
//  Created by Shadowfacts on 1/27/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import SwiftUI
import Pachyderm

struct AddInstancePinnedTimelineView: UIViewControllerRepresentable {
    typealias UIViewControllerType = UINavigationController
    
    @Binding var pinnedTimelines: [PinnedTimeline]
    @Environment(\.dismiss) private var dismiss
    
    func makeUIViewController(context: Context) -> UINavigationController {
        let vc = InstanceSelectorTableViewController()
        vc.title = "Add Instance"
        vc.delegate = context.coordinator
        vc.navigationItem.leftBarButtonItem = UIBarButtonItem(systemItem: .cancel, primaryAction: UIAction(handler: { _ in
            dismiss()
        }))
        return UINavigationController(rootViewController: vc)
    }
    
    func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
    }
    
    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator()
        coordinator.didSelect = {
            pinnedTimelines.append(.instance($0))
            dismiss()
        }
        return coordinator
    }
    
    class Coordinator: InstanceSelectorTableViewControllerDelegate {
        var didSelect: ((URL) -> Void)?
        
        func didSelectInstance(url: URL) {
            didSelect?(url)
        }
    }
}
