2022-11-11 22:51:23 +00:00
//
// C r e a t e L i s t S e r v i c e . s w i f t
// T u s k e r
//
// C r e a t e d b y S h a d o w f a c t s o n 1 1 / 1 1 / 2 2 .
// C o p y r i g h t © 2 0 2 2 S h a d o w f a c t s . A l l r i g h t s r e s e r v e d .
//
import UIKit
import Pachyderm
@ MainActor
class CreateListService {
private let mastodonController : MastodonController
private let present : ( UIViewController ) -> Void
2023-02-19 20:23:25 +00:00
private let didCreateList : ( @ MainActor ( List ) async -> Void ) ?
2022-11-11 22:51:23 +00:00
private var createAction : UIAlertAction ?
2023-02-19 20:23:25 +00:00
init ( mastodonController : MastodonController , present : @ escaping ( UIViewController ) -> Void , didCreateList : ( @ MainActor ( List ) async -> Void ) ? ) {
2022-11-11 22:51:23 +00:00
self . mastodonController = mastodonController
self . present = present
self . didCreateList = didCreateList
}
func run ( ) {
let alert = UIAlertController ( title : NSLocalizedString ( " New List " , comment : " new list alert title " ) , message : NSLocalizedString ( " Choose a title for your new list " , comment : " new list alert message " ) , preferredStyle : . alert )
alert . addTextField { textField in
textField . addTarget ( self , action : #selector ( self . alertTextFieldValueChanged ) , for : . editingChanged )
}
alert . addAction ( UIAlertAction ( title : NSLocalizedString ( " Cancel " , comment : " new list alert cancel button " ) , style : . cancel , handler : nil ) )
createAction = UIAlertAction ( title : NSLocalizedString ( " Create List " , comment : " new list create button " ) , style : . default , handler : { ( _ ) in
let textField = alert . textFields ! . first !
let title = textField . text ? ? " "
Task {
await self . createList ( with : title )
}
} )
createAction ! . isEnabled = false
alert . addAction ( createAction ! )
present ( alert )
}
@objc private func alertTextFieldValueChanged ( _ textField : UITextField ) {
createAction ? . isEnabled = textField . text ? . trimmingCharacters ( in : . whitespacesAndNewlines ) . isEmpty = = false
}
private func createList ( with title : String ) async {
do {
let request = Client . createList ( title : title )
let ( list , _ ) = try await mastodonController . run ( request )
2022-11-19 19:08:39 +00:00
mastodonController . addedList ( list )
2023-02-19 20:23:25 +00:00
await self . didCreateList ? ( list )
2022-11-11 22:51:23 +00:00
} catch {
let alert = UIAlertController ( title : " Error Creating List " , message : error . localizedDescription , preferredStyle : . alert )
alert . addAction ( UIAlertAction ( title : " Cancel " , style : . cancel ) )
alert . addAction ( UIAlertAction ( title : " Retry " , style : . default , handler : { _ in
Task {
await self . createList ( with : title )
}
} ) )
present ( alert )
}
}
}