import Foundation import Postbox import TelegramApi public final class SuggestedPostMessageAttribute: Equatable, MessageAttribute { public enum State: Int32 { case accepted = 0 case rejected = 1 } public let amount: Int64 public let timestamp: Int32? public let state: State? public init(amount: Int64, timestamp: Int32?, state: State?) { self.amount = amount self.timestamp = timestamp self.state = state } required public init(decoder: PostboxDecoder) { self.amount = decoder.decodeInt64ForKey("am", orElse: 0) self.timestamp = decoder.decodeOptionalInt32ForKey("ts") self.state = decoder.decodeOptionalInt32ForKey("st").flatMap(State.init(rawValue:)) } public func encode(_ encoder: PostboxEncoder) { encoder.encodeInt64(self.amount, forKey: "am") if let timestamp = self.timestamp { encoder.encodeInt32(timestamp, forKey: "ts") } else { encoder.encodeNil(forKey: "ts") } if let state = self.state { encoder.encodeInt32(state.rawValue, forKey: "st") } else { encoder.encodeNil(forKey: "st") } } public static func ==(lhs: SuggestedPostMessageAttribute, rhs: SuggestedPostMessageAttribute) -> Bool { if lhs.amount != rhs.amount { return false } if lhs.timestamp != rhs.timestamp { return false } if lhs.state != rhs.state { return false } return true } } extension SuggestedPostMessageAttribute { convenience init(apiSuggestedPost: Api.SuggestedPost) { switch apiSuggestedPost { case let .suggestedPost(flags, starsAmount, scheduleDate): var state: State? if (flags & (1 << 1)) != 0 { state = .accepted } else if (flags & (1 << 2)) != 0 { state = .rejected } self.init(amount: starsAmount, timestamp: scheduleDate, state: state) } } func apiSuggestedPost() -> Api.SuggestedPost { var flags: Int32 = 0 if let state = self.state { switch state { case .accepted: flags |= 1 << 1 case .rejected: flags |= 1 << 2 } } if self.timestamp != nil { flags |= 1 << 0 } return .suggestedPost(flags: flags, starsAmount: self.amount, scheduleDate: self.timestamp) } }