//
//  MyProfileViewController.swift
//  Tusker
//
//  Created by Shadowfacts on 11/24/18.
//  Copyright © 2018 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm
import SwiftUI

class MyProfileViewController: ProfileViewController {

    init(mastodonController: MastodonController) {
        super.init(accountID: nil, mastodonController: mastodonController)
        
        title = "My Profile"
        tabBarItem.image = UIImage(systemName: "person.fill")
        
        mastodonController.getOwnAccount { (result) in
            guard case let .success(account) = result else { return }
            
            DispatchQueue.main.async {
                self.accountID = account.id
                self.setAvatarTabBarImage(account: account)
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Preferences", style: .plain, target: self, action: #selector(preferencesPressed))
        
        NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil)
    }
    
    override func updateUserActivity() {
        userActivity = UserActivityManager.myProfileActivity(accountID: mastodonController.accountInfo!.id)
    }
    
    override func stateRestorationActivity() -> NSUserActivity? {
        return UserActivityManager.myProfileActivity(accountID: mastodonController.accountInfo!.id)
    }
    
    private func setAvatarTabBarImage<Account: AccountProtocol>(account: Account) {
        guard let avatarURL = account.avatar else { return }
        _ = ImageCache.avatars.get(avatarURL, completion: { [weak self] (_, image) in
            guard let self = self,
                  let image = image,
                  let maybeGrayscale = ImageGrayscalifier.convertIfNecessary(url: avatarURL, image: image) else {
                return
            }
            
            DispatchQueue.main.async {
                let size = CGSize(width: 30, height: 30)
                let rect = CGRect(origin: .zero, size: size)
                let tabBarImage = UIGraphicsImageRenderer(size: size).image { (_) in
                    let radius = Preferences.shared.avatarStyle.cornerRadiusFraction * 30
                    UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
                    maybeGrayscale.draw(in: rect)
                }
                let alwaysOriginalImage = tabBarImage.withRenderingMode(.alwaysOriginal)
                self.tabBarItem.image = alwaysOriginalImage
            }
        })
    }
    
    @objc private func preferencesChanged() {
        guard let id = mastodonController.account?.id,
           let account = mastodonController.persistentContainer.account(for: id) else {
            return
        }
        
        setAvatarTabBarImage(account: account)
    }
    
    // MARK: - Interaction
    
    @objc func preferencesPressed() {
        present(PreferencesNavigationController(mastodonController: mastodonController), animated: true)
    }

}
