//
//  Poll.swift
//  Pachyderm
//
//  Created by Shadowfacts on 4/25/21.
//  Copyright © 2021 Shadowfacts. All rights reserved.
//

import Foundation

public struct Poll: Codable, Sendable {
    public let id: String
    public let expiresAt: Date?
    public let expired: Bool
    public let multiple: Bool
    public let votesCount: Int
    public let votersCount: Int?
    public let voted: Bool?
    public let ownVotes: [Int]?
    public let options: [Option]
    public let emojis: [Emoji]
    
    public var effectiveExpired: Bool {
        expired || (expiresAt != nil && expiresAt! < Date())
    }
    
    public static func vote(_ pollID: String, choices: [Int]) -> Request<Poll> {
        return Request<Poll>(method: .post, path: "/api/v1/polls/\(pollID)/votes", body: FormDataBody("choices" => choices, nil))
    }
    
    private enum CodingKeys: String, CodingKey {
        case id
        case expiresAt = "expires_at"
        case expired
        case multiple
        case votesCount = "votes_count"
        case votersCount = "voters_count"
        case voted
        case ownVotes = "own_votes"
        case options
        case emojis
    }
}

extension Poll {
    public struct Option: Codable, Sendable {
        public let title: String
        public let votesCount: Int?
        
        private enum CodingKeys: String, CodingKey {
            case title
            case votesCount = "votes_count"
        }
    }
}
