//
//  OnboardingData.swift
//  Feels (iOS)
//
//  Created by Trey Tartt on 1/22/22.
//

import Foundation

// this is getting passed around and filled out
// class and vars
final class OnboardingData: NSObject, ObservableObject, Codable {
    @Published var date: Date = Date()
    @Published var inputDay: DayOptions = .Today
    @Published var title: String = OnboardingTitle.titleOptions[0]
    
    enum CodingKeys: CodingKey {
        case date, inputDay, title
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(date, forKey: .date)
        try container.encode(inputDay, forKey: .inputDay)
        try container.encode(title, forKey: .title)
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        date = try container.decode(Date.self, forKey: .date)
        inputDay = try container.decode(DayOptions.self, forKey: .inputDay)
        title = try container.decode(String.self, forKey: .title)
    }
    
    func ableToVoteBasedOnCurentTime() -> Bool {
        let currentDateComp = Calendar.current.dateComponents([.hour, .minute], from: Date())
        let savedDateComp = Calendar.current.dateComponents([.hour, .minute], from: self.date)

        if let currentHour = currentDateComp.hour,
           let currentMin = currentDateComp.minute,
           let savedHour = savedDateComp.hour,
           let savedMin = savedDateComp.minute {
            
            if currentHour > savedHour {
                return true
            }
            
            if currentHour == savedHour {
                return currentMin >= savedMin
            }
        }
        
        return false
    }
    
    override init() { }
}

extension OnboardingData: RawRepresentable {
    convenience init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
            let result = try? JSONDecoder().decode(OnboardingData.self, from: data)
        else {
            return nil
        }
        self.init()
        
        self.date = result.date
        self.inputDay = result.inputDay
        self.title = result.title
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
            let result = String(data: data, encoding: .utf8)
        else {
            return "[]"
        }
        return result
    }
}
