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

import UIKit
import Pachyderm
import Combine

class ListTimelineViewController: TimelineViewController {

    private(set) var list: List
    
    var presentEditOnAppear = false
    
    private var listRenamedCancellable: AnyCancellable?
    
    init(for list: List, mastodonController: MastodonController) {
        self.list = list
        
        super.init(for: .list(id: list.id), mastodonController: mastodonController)
        
        listChanged()
        
        listRenamedCancellable = mastodonController.$lists
            .compactMap { $0.first { $0.id == list.id } }
            .removeDuplicates(by: { $0.title == $1.title })
            .sink { [unowned self] in
                self.list = $0
                self.listChanged()
            }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editListButtonPressed))
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if presentEditOnAppear {
            presentEdit(animated: true)
            presentEditOnAppear = false
        }
    }
    
    private func listChanged() {
        title = list.title
    }
    
    func presentEdit(animated: Bool) {
        let editListAccountsController = EditListAccountsViewController(list: list, mastodonController: mastodonController)
        editListAccountsController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(editListDoneButtonPressed))
        let navController = UINavigationController(rootViewController: editListAccountsController)
        present(navController, animated: animated)
    }
    
    // MARK: - Interaction
    
    @objc func editListButtonPressed() {
        presentEdit(animated: true)
    }
    
    @objc func editListDoneButtonPressed() {
        let presented = (presentedViewController as? UINavigationController)?.viewControllers.first as? EditListAccountsViewController
        
        dismiss(animated: true)
        
        if presented?.changedAccounts == true {
            Task {
                applyInitialSnapshot()
                await controller.loadInitial()
            }
        }
    }

}
