aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Hotline/HotlineClientNew.swift
blob: 854c7ffdda0d659f745c84f5745e454a911162c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
import Foundation
import Network

// MARK: - Events

/// Events that can be received from a Hotline server
///
/// These are unsolicited messages sent by the server (not replies to requests).
/// Subscribe to the `events` stream to receive them.
public enum HotlineEvent: Sendable {
  /// Server sent a chat message
  case chatMessage(String)
  /// A user's information changed (name, icon, status)
  case userChanged(HotlineUser)
  /// A user disconnected from the server
  case userDisconnected(UInt16)
  /// Server sent a broadcast message
  case serverMessage(String)
  /// Received a private message from a user
  case privateMessage(userID: UInt16, message: String)
  /// Server sent a news post notification
  case newsPost(String)
  /// Server is requesting agreement acceptance
  case agreementRequired(String)
  /// Server sent user access permissions
  case userAccess(HotlineUserAccessOptions)
}

// MARK: - Errors

/// Errors that can occur during Hotline operations
public enum HotlineClientError: Error {
  /// Connection failed
  case connectionFailed(Error)
  /// Server responded with an error code
  case serverError(code: UInt32, message: String?)
  /// Transaction timed out waiting for reply
  case timeout
  /// Client is not connected
  case notConnected
  /// Invalid response from server
  case invalidResponse
  /// Login failed
  case loginFailed(String?)
  
  var userMessage: String {
    switch self {
    case .connectionFailed:
      "Failed to connect to server"
    case .serverError(let code, let message):
      message ?? "Server error: \(code)"
    case .timeout:
      "Request could not be completed"
    case .notConnected:
      "Not connected"
    case .invalidResponse:
      "Server returned an invalid response"
    case .loginFailed(let message):
      message ?? "Login failed"
    }
  }
}

// MARK: - Login Info

/// Information needed to log in to a Hotline server
public struct HotlineLogin: Sendable {
  let login: String
  let password: String
  let username: String
  let iconID: UInt16

  public init(login: String, password: String, username: String, iconID: UInt16) {
    self.login = login
    self.password = password
    self.username = username
    self.iconID = iconID
  }
}

// MARK: - Server Info

/// Information about the connected server
public struct HotlineServerInfo: Sendable {
  let name: String
  let version: UInt16

  public init(name: String, version: UInt16) {
    self.name = name
    self.version = version
  }
}

// MARK: - Hotline Client

/// Modern async/await-based Hotline protocol client
///
/// Example usage:
/// ```swift
/// let client = try await HotlineClientNew.connect(
///   host: "server.example.com",
///   port: 5500,
///   login: HotlineLogin(login: "guest", password: "", username: "John", iconID: 414)
/// )
///
/// // Listen for events
/// Task {
///   for await event in client.events {
///     switch event {
///     case .chatMessage(let text):
///       print("Chat: \(text)")
///     case .userChanged(let user):
///       print("User changed: \(user.name)")
///     default:
///       break
///     }
///   }
/// }
///
/// // Send chat message
/// try await client.sendChat("Hello world!")
///
/// // Get user list
/// let users = try await client.getUserList()
/// ```
public actor HotlineClientNew {
  // MARK: - Properties

  private let socket: NetSocket
  private var serverInfo: HotlineServerInfo?
  private var isConnected: Bool = true

  /// Information about the connected server (name and version)
  public var server: HotlineServerInfo? {
    return serverInfo
  }

  // Event streaming
  private let eventContinuation: AsyncStream<HotlineEvent>.Continuation
  public let events: AsyncStream<HotlineEvent>

  // Transaction tracking for request/reply pattern
  private var pendingTransactions: [UInt32: CheckedContinuation<HotlineTransaction, Error>] = [:]

  private enum TransactionWaitError: Error {
    case timeout
  }

  // Receive loop task
  private var receiveTask: Task<Void, Never>?

  // Keep-alive timer
  private var keepAliveTask: Task<Void, Never>?

  // MARK: - Static Handshake

  private static let handshakeData = Data(endian: .big, {
    "TRTP".fourCharCode() // 'TRTP' protocol ID
    "HOTL".fourCharCode() // 'HOTL' sub-protocol ID
    UInt16(0x0001) // Version
    UInt16(0x0002) // Sub-version
  })
  
  // Transaction IDs
  private var nextTransactionID: UInt32 = 1
  private func generateTransactionID() -> UInt32 {
    defer { self.nextTransactionID += 1 }
    return self.nextTransactionID
  }

  // MARK: - Connection

  /// Connect to a Hotline server and log in
  ///
  /// This method:
  /// 1. Establishes TCP connection
  /// 2. Performs handshake
  /// 3. Logs in with provided credentials
  /// 4. Starts event streaming and keep-alive
  ///
  /// - Parameters:
  ///   - host: Server hostname or IP address
  ///   - port: Server port (default: 5500)
  ///   - login: Login credentials and user info
  ///   - tls: TLS policy (default: disabled for Hotline)
  /// - Returns: Connected and logged-in client
  /// - Throws: `HotlineClientError` if connection or login fails
  public static func connect(
    host: String,
    port: UInt16 = 5500,
    login: HotlineLogin
  ) async throws -> HotlineClientNew {
    print("HotlineClientNew.connect(): Starting connection to \(host):\(port) as '\(login.username)'")

    // Connect socket
    print("HotlineClientNew.connect(): Connecting socket...")
    let socket = try await NetSocket.connect(host: host, port: port)
    print("HotlineClientNew.connect(): Socket connected")

    // Perform handshake
    print("HotlineClientNew.connect(): Sending handshake...")
    try await socket.write(handshakeData)
    let handshakeResponse = try await socket.read(8)
    print("HotlineClientNew.connect(): Handshake response received")

    // Verify handshake
    guard handshakeResponse.prefix(4) == Data([0x54, 0x52, 0x54, 0x50]) else {
      print("HotlineClientNew.connect(): Invalid handshake response")
      throw HotlineClientError.connectionFailed(
        NSError(domain: "HotlineClient", code: -1, userInfo: [
          NSLocalizedDescriptionKey: "Invalid handshake response"
        ])
      )
    }

    let errorCode = handshakeResponse.withUnsafeBytes { $0.load(fromByteOffset: 4, as: UInt32.self) }
    guard errorCode.bigEndian == 0 else {
      print("HotlineClientNew.connect(): Handshake failed with error code \(errorCode)")
      throw HotlineClientError.connectionFailed(
        NSError(domain: "HotlineClient", code: Int(errorCode), userInfo: [
          NSLocalizedDescriptionKey: "Handshake failed with error code \(errorCode)"
        ])
      )
    }

    // Create client
    print("HotlineClientNew.connect(): Creating client instance")
    let client = HotlineClientNew(socket: socket)

    // Start receive loop
    print("HotlineClientNew.connect(): Starting receive loop")
    await client.startReceiveLoop()

    // Perform login
    print("HotlineClientNew.connect(): Performing login")
    let serverInfo = try await client.performLogin(login)
    await client.setServerInfo(serverInfo)
    print("HotlineClientNew.connect(): Login successful")

    // Start keep-alive
    print("HotlineClientNew.connect(): Starting keep-alive")
    await client.startKeepAlive()

    print("HotlineClientNew.connect(): Connected to \(serverInfo.name) (v\(serverInfo.version))")

    return client
  }

  private init(socket: NetSocket) {
    self.socket = socket

    // Set up event stream
    var continuation: AsyncStream<HotlineEvent>.Continuation!
    self.events = AsyncStream { cont in
      continuation = cont
    }
    self.eventContinuation = continuation
  }

  private func setServerInfo(_ info: HotlineServerInfo) {
    self.serverInfo = info
  }

  // MARK: - Login

  private func performLogin(_ login: HotlineLogin) async throws -> HotlineServerInfo {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .login)
    transaction.setFieldEncodedString(type: .userLogin, val: login.login)
    transaction.setFieldEncodedString(type: .userPassword, val: login.password)
    transaction.setFieldUInt16(type: .userIconID, val: login.iconID)
    transaction.setFieldString(type: .userName, val: login.username)
    transaction.setFieldUInt32(type: .versionNumber, val: 123)

    let reply = try await sendTransaction(transaction)
    
    guard reply.errorCode == 0 else {
      let errorText = reply.getField(type: .errorText)?.getString()
      throw HotlineClientError.loginFailed(errorText)
    }

    let serverName = reply.getField(type: .serverName)?.getString() ?? "Unknown"
    let serverVersion = reply.getField(type: .versionNumber)?.getUInt16() ?? 0

    return HotlineServerInfo(name: serverName, version: serverVersion)
  }

  // MARK: - Disconnect

  /// Disconnect from the server
  ///
  /// Closes the socket and stops all background tasks.
  public func disconnect() async {
    guard isConnected else {
      return
    }

    isConnected = false

    print("HotlineClientNew.disconnect(): Starting disconnect")
    self.receiveTask?.cancel()
    self.keepAliveTask?.cancel()
    await self.socket.close()
    self.failAllPendingTransactions(HotlineClientError.notConnected)
    self.eventContinuation.finish()
    print("HotlineClientNew.disconnect(): Disconnect complete")
  }

  // MARK: - Receive Loop

  private func startReceiveLoop() {
    print("HotlineClientNew.startReceiveLoop(): Creating receive task")
    self.receiveTask = Task { [weak self] in
      guard let self else {
        return
      }

      do {
        while !Task.isCancelled {
          // Read transaction from socket
          let transaction = try await self.socket.receive(HotlineTransaction.self, endian: .big)
          await self.handleTransaction(transaction)
        }
        print("HotlineClientNew.startReceiveLoop(): Task cancelled, exiting loop")
      } catch {
        if Task.isCancelled || error is CancellationError {
          print("HotlineClientNew.startReceiveLoop(): Receive loop cancelled")
        } else {
          print("HotlineClientNew.startReceiveLoop(): Receive loop error: \(error)")
          await self.disconnect()
        }
      }
      print("HotlineClientNew.startReceiveLoop(): Receive loop ended")
    }
  }

  private func handleTransaction(_ transaction: HotlineTransaction) {
    print("HotlineClientNew: <= \(transaction.type) [\(transaction.id)]")

    // Check if this is a reply to a pending transaction
    if transaction.isReply == 1 || transaction.type == .reply {
      handleReply(transaction)
      return
    }

    // Handle unsolicited server messages (events)
    handleEvent(transaction)
  }

  private func handleReply(_ transaction: HotlineTransaction) {
    guard let continuation = pendingTransactions.removeValue(forKey: transaction.id) else {
      print("HotlineClientNew: Received reply for unknown transaction \(transaction.id)")
      return
    }

    if transaction.errorCode != 0 {
      let errorText = transaction.getField(type: .errorText)?.getString()
      continuation.resume(throwing: HotlineClientError.serverError(
        code: transaction.errorCode,
        message: errorText
      ))
    } else {
      print("HELLO")
      continuation.resume(returning: transaction)
    }
  }

  private func handleEvent(_ transaction: HotlineTransaction) {
    switch transaction.type {
    case .chatMessage:
      if let text = transaction.getField(type: .data)?.getString() {
        eventContinuation.yield(.chatMessage(text))
      }

    case .notifyOfUserChange:
      if let usernameField = transaction.getField(type: .userName),
         let username = usernameField.getString(),
         let userID = transaction.getField(type: .userID)?.getUInt16(),
         let iconID = transaction.getField(type: .userIconID)?.getUInt16(),
         let flags = transaction.getField(type: .userFlags)?.getUInt16() {
        let user = HotlineUser(id: userID, iconID: iconID, status: flags, name: username)
        eventContinuation.yield(.userChanged(user))
      }

    case .notifyOfUserDelete:
      if let userID = transaction.getField(type: .userID)?.getUInt16() {
        eventContinuation.yield(.userDisconnected(userID))
      }

    case .serverMessage:
      if let message = transaction.getField(type: .data)?.getString() {
        if let userID = transaction.getField(type: .userID)?.getUInt16() {
          eventContinuation.yield(.privateMessage(userID: userID, message: message))
        } else {
          eventContinuation.yield(.serverMessage(message))
        }
      }

    case .showAgreement:
      if transaction.getField(type: .noServerAgreement) == nil,
         let agreementText = transaction.getField(type: .data)?.getString() {
        eventContinuation.yield(.agreementRequired(agreementText))
      }

    case .userAccess:
      if let accessValue = transaction.getField(type: .userAccess)?.getUInt64() {
        eventContinuation.yield(.userAccess(HotlineUserAccessOptions(rawValue: accessValue)))
      }

    case .newMessage:
      if let message = transaction.getField(type: .data)?.getString() {
        eventContinuation.yield(.newsPost(message))
      }

    case .disconnectMessage:
      Task {
        await self.disconnect()
      }

    default:
      print("HotlineClientNew: Unhandled event type \(transaction.type)")
    }
  }

  // MARK: - Transaction Sending

  private func sendTransaction(_ transaction: HotlineTransaction, timeout: TimeInterval = 30.0) async throws -> HotlineTransaction {
    print("HotlineClientNew: => \(transaction.type) [\(transaction.id)]")

    let transactionID = transaction.id

    try await self.socket.send(transaction, endian: .big)

    do {
      return try await withTimeout(seconds: timeout) {
        try await self.awaitReply(for: transactionID)
      }
    } catch is TransactionWaitError {
      throw HotlineClientError.timeout
    } catch let error as HotlineClientError {
      throw error
    } catch {
      throw error
    }
  }

  private func storePendingTransaction(id: UInt32, continuation: CheckedContinuation<HotlineTransaction, Error>) {
    self.pendingTransactions[id] = continuation
  }

  private func awaitReply(for transactionID: UInt32) async throws -> HotlineTransaction {
    try await withTaskCancellationHandler {
      try await withCheckedThrowingContinuation { continuation in
        self.storePendingTransaction(id: transactionID, continuation: continuation)
      }
    } onCancel: { [weak self] in
      Task { await self?.failPendingTransaction(id: transactionID, error: HotlineClientError.timeout) }
    }
  }

  private func failPendingTransaction(id: UInt32, error: Error) {
    guard let continuation = self.pendingTransactions.removeValue(forKey: id) else { return }
    continuation.resume(throwing: error)
  }

  private func failAllPendingTransactions(_ error: Error) {
    guard !self.pendingTransactions.isEmpty else { return }
    let continuations = self.pendingTransactions
    self.pendingTransactions.removeAll()
    for (_, continuation) in continuations {
      continuation.resume(throwing: error)
    }
  }

  private func withTimeout<T>(seconds: TimeInterval, operation: @escaping @Sendable () async throws -> T) async throws -> T {
    if seconds <= 0 {
      throw TransactionWaitError.timeout
    }

    return try await withThrowingTaskGroup(of: T.self) { group in
      group.addTask {
        try await operation()
      }

      group.addTask {
        try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
        throw TransactionWaitError.timeout
      }

      do {
        let value = try await group.next()!
        group.cancelAll()
        return value
      } catch {
        group.cancelAll()
        throw error
      }
    }
  }

  // MARK: - Keep-Alive

  private func startKeepAlive() {
    self.keepAliveTask = Task { [weak self] in
      while !Task.isCancelled {
        try? await Task.sleep(nanoseconds: 180_000_000_000) // 3 minutes
        await self?.sendKeepAlive()
      }
    }
  }
  
  private func sendKeepAlive() async {
    do {
      if let version = self.serverInfo?.version, version >= 185 {
        let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .connectionKeepAlive)
        try await self.socket.send(transaction, endian: .big)
      } else {
        // Older servers: send getUserNameList as keep-alive
        let _ = try? await self.getUserList()
      }
    } catch {
      print("HotlineClientNew: Keep-alive failed: \(error)")
    }
  }

  // MARK: - Chat

  /// Send a chat message to the server
  ///
  /// - Parameters:
  ///   - message: Text to send
  ///   - encoding: Text encoding (default: UTF-8)
  ///   - announce: Whether this is an announcement (admin only, default: false)
  public func sendChat(_ message: String, encoding: String.Encoding = .utf8, announce: Bool = false) async throws {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .sendChat)
    transaction.setFieldString(type: .data, val: message, encoding: encoding)
    transaction.setFieldUInt16(type: .chatOptions, val: announce ? 1 : 0)

    try await socket.send(transaction, endian: .big)
  }

  // MARK: - Users

  /// Get the list of users currently connected to the server
  ///
  /// - Returns: Array of connected users
  public func getUserList() async throws -> [HotlineUser] {
    let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getUserNameList)
    let reply = try await sendTransaction(transaction)

    var users: [HotlineUser] = []
    for field in reply.getFieldList(type: .userNameWithInfo) {
      users.append(field.getUser())
    }

    return users
  }

  /// Send a private instant message to a user
  ///
  /// - Parameters:
  ///   - message: Text to send
  ///   - userID: Target user ID
  ///   - encoding: Text encoding (default: UTF-8)
  public func sendInstantMessage(_ message: String, to userID: UInt16, encoding: String.Encoding = .utf8) async throws {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .sendInstantMessage)
    transaction.setFieldUInt16(type: .userID, val: userID)
    transaction.setFieldUInt32(type: .options, val: 1)
    transaction.setFieldString(type: .data, val: message, encoding: encoding)

    try await socket.send(transaction, endian: .big)
  }

  /// Update this client's user info (name, icon, options)
  ///
  /// - Parameters:
  ///   - username: Display name
  ///   - iconID: Icon ID
  ///   - options: User options flags
  ///   - autoresponse: Optional auto-response text
  public func setClientUserInfo(
    username: String,
    iconID: UInt16,
    options: HotlineUserOptions = [],
    autoresponse: String? = nil
  ) async throws {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .setClientUserInfo)
    transaction.setFieldString(type: .userName, val: username)
    transaction.setFieldUInt16(type: .userIconID, val: iconID)
    transaction.setFieldUInt16(type: .options, val: options.rawValue)

    if let autoresponse {
      transaction.setFieldString(type: .automaticResponse, val: autoresponse)
    }

    try await socket.send(transaction, endian: .big)
  }

  // MARK: - Agreement

  /// Send agreement acceptance to the server
  ///
  /// Call this after receiving `.agreementRequired` event.
  public func sendAgree() async throws {
    let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .agreed)
    try await socket.send(transaction, endian: .big)
  }

  // MARK: - Public API - Files

  /// Get the file list for a directory
  ///
  /// - Parameter path: Directory path (empty for root)
  /// - Returns: Array of files and folders
  public func getFileList(path: [String] = []) async throws -> [HotlineFile] {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getFileNameList)
    if !path.isEmpty {
      transaction.setFieldPath(type: .filePath, val: path)
    }

    let reply = try await sendTransaction(transaction)

    var files: [HotlineFile] = []
    for field in reply.getFieldList(type: .fileNameWithInfo) {
      let file = field.getFile()
      file.path = path + [file.name]
      files.append(file)
    }

    return files
  }

  /// Request to download a file
  ///
  /// - Parameters:
  ///   - name: File name
  ///   - path: Directory path containing the file
  ///   - preview: Request preview/thumbnail instead of full file
  /// - Returns: Transfer info (reference number, size, waiting count)
  public func downloadFile(
    name: String,
    path: [String],
    preview: Bool = false
  ) async throws -> (referenceNumber: UInt32, size: Int, fileSize: Int?, waitingCount: Int?) {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadFile)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)

    if preview {
      transaction.setFieldUInt32(type: .fileTransferOptions, val: 2)
    }

    let reply = try await sendTransaction(transaction)

    guard
      let transferSize = reply.getField(type: .transferSize)?.getInteger(),
      let referenceNumber = reply.getField(type: .referenceNumber)?.getUInt32()
    else {
      throw HotlineClientError.invalidResponse
    }

    let fileSize = reply.getField(type: .fileSize)?.getInteger()
    let waitingCount = reply.getField(type: .waitingCount)?.getInteger()

    return (referenceNumber, transferSize, fileSize, waitingCount)
  }

  // MARK: - Public API - News

  /// Get news categories at a path
  ///
  /// - Parameter path: Category path (empty for root)
  /// - Returns: Array of news categories
  public func getNewsCategories(path: [String] = []) async throws -> [HotlineNewsCategory] {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getNewsCategoryNameList)
    if !path.isEmpty {
      transaction.setFieldPath(type: .newsPath, val: path)
    }

    let reply = try await sendTransaction(transaction)

    var categories: [HotlineNewsCategory] = []
    for field in reply.getFieldList(type: .newsCategoryListData15) {
      var category = field.getNewsCategory()
      category.path = path + [category.name]
      categories.append(category)
    }

    return categories
  }

  /// Get news articles in a category
  ///
  /// - Parameter path: Category path
  /// - Returns: Array of news articles
  public func getNewsArticles(path: [String] = []) async throws -> [HotlineNewsArticle] {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getNewsArticleNameList)
    if !path.isEmpty {
      transaction.setFieldPath(type: .newsPath, val: path)
    }

    let reply = try await sendTransaction(transaction)

    guard let articleData = reply.getField(type: .newsArticleListData) else {
      return []
    }

    let newsList = articleData.getNewsList()
    return newsList.articles.map { article in
      var a = article
      a.path = path
      return a
    }
  }

  /// Get the content of a news article
  ///
  /// - Parameters:
  ///   - id: Article ID
  ///   - path: Category path
  ///   - flavor: Content flavor (default: "text/plain")
  /// - Returns: Article content as string
  public func getNewsArticle(id: UInt32, path: [String], flavor: String = "text/plain") async throws -> String? {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getNewsArticleData)
    transaction.setFieldPath(type: .newsPath, val: path)
    transaction.setFieldUInt32(type: .newsArticleID, val: id)
    transaction.setFieldString(type: .newsArticleDataFlavor, val: flavor, encoding: .ascii)

    let reply = try await sendTransaction(transaction)
    return reply.getField(type: .newsArticleData)?.getString()
  }

  /// Post a news article
  ///
  /// - Parameters:
  ///   - title: Article title
  ///   - text: Article body
  ///   - path: Category path
  ///   - parentID: Parent article ID (for replies, default: 0)
  public func postNewsArticle(
    title: String,
    text: String,
    path: [String],
    parentID: UInt32 = 0
  ) async throws {
    guard !path.isEmpty else {
      throw HotlineClientError.invalidResponse
    }

    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .postNewsArticle)
    transaction.setFieldPath(type: .newsPath, val: path)
    transaction.setFieldUInt32(type: .newsArticleID, val: parentID)
    transaction.setFieldString(type: .newsArticleTitle, val: title)
    transaction.setFieldString(type: .newsArticleDataFlavor, val: "text/plain")
    transaction.setFieldUInt32(type: .newsArticleFlags, val: 0)
    transaction.setFieldString(type: .newsArticleData, val: text)

    _ = try await sendTransaction(transaction)
  }

  // MARK: - Public API - Message Board

  /// Get message board posts
  ///
  /// - Returns: Array of message strings
  public func getMessageBoard() async throws -> [String] {
    let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getMessageBoard)
    let reply = try await sendTransaction(transaction)

    guard let text = reply.getField(type: .data)?.getString() else {
      return []
    }

    // Parse messages (separated by divider pattern)
    // TODO: Implement proper divider parsing if needed
    return [text]
  }

  /// Post to the message board
  ///
  /// - Parameter text: Message text
  public func postMessageBoard(_ text: String) async throws {
    guard !text.isEmpty else { return }

    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .oldPostNews)
    transaction.setFieldString(type: .data, val: text, encoding: .macOSRoman)

    try await socket.send(transaction, endian: .big)
  }

  // MARK: - Public API - File Operations

  /// Get detailed information about a file
  ///
  /// - Parameters:
  ///   - name: File name
  ///   - path: Directory path containing the file
  /// - Returns: File details or nil if not found
  public func getFileInfo(name: String, path: [String]) async throws -> FileDetails? {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getFileInfo)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)

    let reply = try await sendTransaction(transaction)

    guard
      let fileName = reply.getField(type: .fileName)?.getString(),
      let fileCreator = reply.getField(type: .fileCreatorString)?.getString(),
      let fileType = reply.getField(type: .fileTypeString)?.getString(),
      let fileCreateDate = reply.getField(type: .fileCreateDate)?.data.readDate(at: 0),
      let fileModifyDate = reply.getField(type: .fileModifyDate)?.data.readDate(at: 0)
    else {
      return nil
    }

    // Size field is not included in server reply for folders
    let fileSize = reply.getField(type: .fileSize)?.getInteger() ?? 0
    let fileComment = reply.getField(type: .fileComment)?.getString() ?? ""

    return FileDetails(
      name: fileName,
      path: path,
      size: fileSize,
      comment: fileComment,
      type: fileType,
      creator: fileCreator,
      created: fileCreateDate,
      modified: fileModifyDate
    )
  }

  /// Delete a file or folder
  ///
  /// - Parameters:
  ///   - name: File or folder name
  ///   - path: Directory path containing the item
  /// - Returns: True if deletion succeeded
  public func deleteFile(name: String, path: [String]) async throws -> Bool {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .deleteFile)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)

    do {
      _ = try await sendTransaction(transaction)
      return true
    } catch {
      return false
    }
  }

  // MARK: - Administration

  /// Get list of user accounts (requires admin access)
  ///
  /// - Returns: Array of user accounts sorted by login
  public func getAccounts() async throws -> [HotlineAccount] {
    let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getAccounts)
    let reply = try await sendTransaction(transaction)

    let accountFields = reply.getFieldList(type: .data)
    var accounts: [HotlineAccount] = []

    for data in accountFields {
      accounts.append(data.getAcccount())
    }

    accounts.sort { $0.login < $1.login }

    return accounts
  }

  /// Create a new user account (requires admin access)
  ///
  /// - Parameters:
  ///   - name: Display name for the user
  ///   - login: Login username
  ///   - password: Optional password (nil for no password)
  ///   - access: Access permissions bitmask
  public func createUser(name: String, login: String, password: String?, access: UInt64) async throws {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .newUser)

    transaction.setFieldString(type: .userName, val: name)
    transaction.setFieldEncodedString(type: .userLogin, val: login)
    transaction.setFieldUInt64(type: .userAccess, val: access)

    if let password {
      transaction.setFieldEncodedString(type: .userPassword, val: password)
    }

    _ = try await sendTransaction(transaction)
  }

  /// Update an existing user account (requires admin access)
  ///
  /// - Parameters:
  ///   - name: Display name for the user
  ///   - login: Current login username
  ///   - newLogin: New login username (nil to keep current)
  ///   - password: Password update - nil to keep current, "" to remove, or new password string
  ///   - access: Access permissions bitmask
  public func setUser(name: String, login: String, newLogin: String?, password: String?, access: UInt64) async throws {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .setUser)
    transaction.setFieldString(type: .userName, val: name)
    transaction.setFieldUInt64(type: .userAccess, val: access)

    if let newLogin {
      transaction.setFieldEncodedString(type: .data, val: login)
      transaction.setFieldEncodedString(type: .userLogin, val: newLogin)
    } else {
      transaction.setFieldEncodedString(type: .userLogin, val: login)
    }

    // Password field handling:
    // - nil: Keep current password (send zero byte)
    // - "": Remove password (omit field)
    // - other: Set new password
    if password == nil {
      transaction.setFieldUInt8(type: .userPassword, val: 0)
    } else if password != "" {
      transaction.setFieldEncodedString(type: .userPassword, val: password!)
    }

    _ = try await sendTransaction(transaction)
  }

  /// Delete a user account (requires admin access)
  ///
  /// - Parameter login: Login username to delete
  public func deleteUser(login: String) async throws {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .deleteUser)
    transaction.setFieldEncodedString(type: .userLogin, val: login)

    _ = try await sendTransaction(transaction)
  }

  // MARK: - Banners

  /// Request to download the server banner image
  ///
  /// - Returns: Tuple of (referenceNumber, transferSize) for the banner download
  /// - Throws: HotlineClientError if not connected or server doesn't support banners
  public func downloadBanner() async throws -> (referenceNumber: UInt32, transferSize: Int)? {
    let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadBanner)
    let reply = try await sendTransaction(transaction)

    guard
      let transferSizeField = reply.getField(type: .transferSize),
      let transferSize = transferSizeField.getInteger(),
      let transferReferenceField = reply.getField(type: .referenceNumber),
      let referenceNumber = transferReferenceField.getUInt32()
    else {
      return nil
    }

    return (referenceNumber, transferSize)
  }

  // MARK: - Transfers

  /// Request to download a file
  ///
  /// - Parameters:
  ///   - name: File name to download
  ///   - path: Directory path containing the file
  ///   - preview: If true, request preview mode (smaller transfer)
  /// - Returns: Tuple of (referenceNumber, transferSize, fileSize, waitingCount) for the download
  public func downloadFile(name: String, path: [String], preview: Bool = false) async throws -> (referenceNumber: UInt32, transferSize: Int, fileSize: Int, waitingCount: Int)? {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadFile)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)

    if preview {
      transaction.setFieldUInt32(type: .fileTransferOptions, val: 2)
    }

    let reply = try await sendTransaction(transaction)

    guard
      let transferSizeField = reply.getField(type: .transferSize),
      let transferSize = transferSizeField.getInteger(),
      let transferReferenceField = reply.getField(type: .referenceNumber),
      let referenceNumber = transferReferenceField.getUInt32()
    else {
      return nil
    }

    let fileSize = reply.getField(type: .fileSize)?.getInteger() ?? transferSize
    let waitingCount = reply.getField(type: .waitingCount)?.getInteger() ?? 0

    return (referenceNumber, transferSize, fileSize, waitingCount)
  }

  /// Request to download a folder
  ///
  /// - Parameters:
  ///   - name: Folder name to download
  ///   - path: Directory path containing the folder
  /// - Returns: Tuple of (referenceNumber, transferSize, itemCount, waitingCount) for the download
  public func downloadFolder(name: String, path: [String]) async throws -> (referenceNumber: UInt32, transferSize: Int, itemCount: Int, waitingCount: Int)? {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadFolder)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)

    let reply = try await sendTransaction(transaction)

    guard
      let transferSizeField = reply.getField(type: .transferSize),
      let transferSize = transferSizeField.getInteger(),
      let transferReferenceField = reply.getField(type: .referenceNumber),
      let referenceNumber = transferReferenceField.getUInt32()
    else {
      return nil
    }

    let itemCount = reply.getField(type: .folderItemCount)?.getInteger() ?? 0
    let waitingCount = reply.getField(type: .waitingCount)?.getInteger() ?? 0

    return (referenceNumber, transferSize, itemCount, waitingCount)
  }

  /// Uploads a file to the server
  /// - Parameters:
  ///   - name: File name to upload
  ///   - path: Directory path where the file should be uploaded
  /// - Returns: Reference number for the upload transfer
  public func uploadFile(name: String, path: [String]) async throws -> UInt32? {
    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .uploadFile)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)

    let reply = try await sendTransaction(transaction)

    guard
      let transferReferenceField = reply.getField(type: .referenceNumber),
      let referenceNumber = transferReferenceField.getUInt32()
    else {
      return nil
    }

    return referenceNumber
  }
  
  /// Request to upload a folder
  ///
  /// - Parameters:
  ///   - name: Folder name to upload
  ///   - path: Directory path where the folder should be uploaded
  /// - Returns: Reference number for the upload transfer
  public func uploadFolder(name: String, path: [String], fileCount: UInt32, totalSize: UInt32) async throws -> UInt32? {
    print("HotlineClientNew: uploadFolder request - name='\(name)', path=\(path), fileCount=\(fileCount), totalSize=\(totalSize)")

    var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .uploadFolder)
    transaction.setFieldString(type: .fileName, val: name)
    transaction.setFieldPath(type: .filePath, val: path)
    transaction.setFieldUInt32(type: .transferSize, val: totalSize)
    transaction.setFieldUInt16(type: .folderItemCount, val: UInt16(truncatingIfNeeded: fileCount))

    let reply = try await sendTransaction(transaction)

    guard
      let transferReferenceField = reply.getField(type: .referenceNumber),
      let referenceNumber = transferReferenceField.getUInt32()
    else {
      return nil
    }

    return referenceNumber
  }
}