//
//  Mention.swift
//  Pachyderm
//
//  Created by Shadowfacts on 9/9/18.
//  Copyright © 2018 Shadowfacts. All rights reserved.
//

import Foundation
import WebURL

public struct Mention: Codable, Sendable {
    public let url: WebURL
    public let username: String
    public let acct: String
    /// The instance-local ID of the user being mentioned.
    public let id: String
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.username = try container.decode(String.self, forKey: .username)
        self.acct = try container.decode(String.self, forKey: .acct)
        self.id = try container.decode(String.self, forKey: .id)
        do {
            self.url = try container.decode(WebURL.self, forKey: .url)
        } catch {
            let s = try? container.decode(String.self, forKey: .url)
            throw DecodingError.dataCorruptedError(forKey: .url, in: container, debugDescription: "Could not decode URL '\(s ?? "<failed to decode string>")'")
        }
    }
    
    public init(url: WebURL, username: String, acct: String, id: String) {
        self.url = url
        self.username = username
        self.acct = acct
        self.id = id
    }
    
    private enum CodingKeys: String, CodingKey {
        case url
        case username
        case acct
        case id
    }
}
