Tusker/Tusker/API/ToggleFollowHashtagService....

68 lines
2.4 KiB
Swift

//
// ToggleFollowHashtagService.swift
// Tusker
//
// Created by Shadowfacts on 11/29/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
@MainActor
class ToggleFollowHashtagService {
private let hashtag: Hashtag
private let mastodonController: MastodonController
private let presenter: any TuskerNavigationDelegate
init(hashtag: Hashtag, presenter: any TuskerNavigationDelegate) {
self.hashtag = hashtag
self.mastodonController = presenter.apiController
self.presenter = presenter
}
func toggleFollow() async {
let context = mastodonController.persistentContainer.viewContext
var config: ToastConfiguration
if let existing = mastodonController.followedHashtags.first(where: { $0.name == hashtag.name }) {
do {
let req = Hashtag.unfollow(name: hashtag.name)
_ = try await mastodonController.run(req)
context.delete(existing)
mastodonController.updateFollowedHashtags()
config = ToastConfiguration(title: "Unfollowed Hashtag")
config.systemImageName = "checkmark"
config.dismissAutomaticallyAfter = 2
} catch {
config = ToastConfiguration(from: error, with: "Error Unfollowing Hashtag", in: presenter) { toast in
toast.dismissToast(animated: true)
await self.toggleFollow()
}
}
} else {
do {
let req = Hashtag.follow(name: hashtag.name)
let (hashtag, _) = try await mastodonController.run(req)
_ = FollowedHashtag(hashtag: hashtag, context: context)
mastodonController.updateFollowedHashtags()
config = ToastConfiguration(title: "Followed Hashtag")
config.systemImageName = "checkmark"
config.dismissAutomaticallyAfter = 2
} catch {
config = ToastConfiguration(from: error, with: "Error Following Hashtag", in: presenter) { toast in
toast.dismissToast(animated: true)
await self.toggleFollow()
}
}
}
presenter.showToast(configuration: config, animated: true)
mastodonController.persistentContainer.save(context: context)
}
}