//
//  NSLayoutConstraintAxis+Extension.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 12/20/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import Foundation

/**
 When using this class in codable for a String value from server.
 
 Example use case....
 
 var axis: NSLayoutConstraint.Axis
 
 enum CodingKeys: String, CodingKey {
     case axis
 }
 
 required public init(from decoder: Decoder) throws {
     let container = try decoder.container(keyedBy: CodingKeys.self)
     let word = try container.decode(String.self, forKey: .axis)
     axis = NSLayoutConstraint.Axis(rawValue: axis)!
 }
 
 public func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
     try container.encode(axis.rawValueString, forKey: .axis)
 }
 */

enum AxisError: Error {
    case notAnAxis
}

extension NSLayoutConstraint.Axis: RawRepresentable {
    
    init?(rawValue: String) {
        switch rawValue {
        case "horizontal":
            self = .horizontal
        case "vertical":
            self = .vertical
        default:
            return nil
        }
    }
    
    var rawValueString: String {
        switch self {
        case .horizontal:
            return "horizontal"
        case .vertical:
            return "vertical"
        @unknown default:
            return ""
        }
    }
}

extension NSLayoutConstraint.Axis: Codable {
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.singleValueContainer()
        let string = try typeContainer.decode(String.self)
        guard let axis = NSLayoutConstraint.Axis(rawValue: string) else {
            throw AxisError.notAnAxis
        }
        self = axis
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValueString)
    }
}
