//
//  LocalAccountAvatarView.swift
//  Tusker
//
//  Created by Shadowfacts on 5/10/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import SwiftUI
import UserAccounts

struct LocalAccountAvatarView: View {
    let localAccountInfo: UserAccountInfo
    @State var avatarImage: UIImage? = nil
    @ObservedObject var preferences = Preferences.shared
    
    var body: some View {
        let image: Image
        if avatarImage == nil {
            let imageName: String
            switch preferences.avatarStyle {
            case .circle:
                imageName = "person.crop.circle"
            case .roundRect:
                imageName = "person.crop.square"
            }
            image = Image(systemName: imageName).resizable()
        } else {
            image = Image(uiImage: self.avatarImage!).renderingMode(.original)
        }
        return image
            .resizable()
            .frame(width: 30, height: 30)
            .cornerRadius(preferences.avatarStyle.cornerRadiusFraction * 30)
            .onAppear(perform: self.loadImage)
    }
    
    func loadImage() {
        let controller = MastodonController.getForAccount(localAccountInfo)
        controller.getOwnAccount { (result) in
            guard case let .success(account) = result,
                  let avatar = account.avatar else { return }
            _ = ImageCache.avatars.get(avatar) { (_, image) in
                DispatchQueue.main.async {
                    self.avatarImage = image
                }
            }
        }
    }
}

//struct LocalAccountAvatarView_Previews: PreviewProvider {
//    static var previews: some View {
//        LocalAccountAvatarView()
//    }
//}
