//
//  UIStackViewAlignment+Extension.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 12/16/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 alignment: UIStackView.Alignment
 
 enum CodingKeys: String, CodingKey {
     case alignment
 }
 
 required public init(from decoder: Decoder) throws {
     let container = try decoder.container(keyedBy: CodingKeys.self)
     let word = try container.decode(String.self, forKey: .alignment)
     alignment = UIStackView.Alignment(rawValue: word)!
 }
 
 public func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
     try container.encode(alignment.rawValueString, forKey: .alignment)
 }
 */

enum AlignmentError: Error {
    case notAnAlignment
}

extension UIStackView.Alignment: RawRepresentable {
    
    init?(rawValue: String) {
        switch rawValue {
        case "fill":
            self = .fill
        case "leading":
            self = .leading
        case "firstBaseline":
            self = .firstBaseline
        case "center":
            self = .center
        case "trailing":
            self = .trailing
        case "lastBaseline":
            self = .lastBaseline
        default:
            return nil
        }
    }
    
    var rawValueString: String {
        switch self {
        case .fill:
            return "fill"
        case .leading:
            return "leading"
        case .firstBaseline:
            return "firstBaseline"
        case .center:
            return "center"
        case .trailing:
            return "trailing"
        case .lastBaseline:
            return "lastBaseline"
        @unknown default:
            return ""
        }
    }
}

extension UIStackView.Alignment: Codable {
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.singleValueContainer()
        let string = try typeContainer.decode(String.self)
        guard let alignment = UIStackView.Alignment(rawValue: string) else {
            throw AlignmentError.notAnAlignment
        }
        self = alignment
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValueString)
    }
}
