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

import Foundation
import UserNotifications

// this is getting passed around and filled out
// class and vars
final class OnboardingData: NSObject, ObservableObject, Codable {
    @Published var date: Date = {
        var components = Calendar.current.dateComponents([.year, .month, .day], from: Date())
        components.hour = 21 // 9 PM default (matches default .Today selection)
        components.minute = 0
        return Calendar.current.date(from: components) ?? Date()
    }()
    @Published var inputDay: DayOptions = .Today
    
    enum CodingKeys: CodingKey {
        case date, inputDay
    }
    
    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)
    }
    
    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)
    }
        
    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
    }

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