//
//  UIContentMode+Extension.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 2/17/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

enum ContentModeError: Error {
    case notAContentMode
}

extension UIView.ContentMode: RawRepresentable {
    
    init?(rawValue: String) {
        switch rawValue {
        case "scaleToFill":
            self = .scaleToFill
        case "scaleAspectFit":
            self = .scaleAspectFit
        case "scaleAspectFill":
            self = .scaleAspectFill
        case "redraw":
            self = .redraw
        case "center":
            self = .center
        case "top":
            self = .top
        case "bottom":
            self = .bottom
         case "left":
            self = .left
        case "right":
            self = .right
        case "topLeft":
            self = .topLeft
        case "topRight":
            self = .topRight
        case "bottomLeft":
            self = .bottomLeft
        case "bottomRight":
            self = .bottomRight
        default:
            return nil
        }
    }
    
    var rawValueString: String {
        switch self {
        case .scaleToFill:
            return "scaleToFill"
        case .scaleAspectFit:
            return "scaleAspectFit"
        case .scaleAspectFill:
            return "scaleAspectFill"
        case .redraw:
            return "redraw"
        case .center:
            return "center"
        case .top:
            return "top"
        case .bottom:
            return "bottom"
        case .left:
            return "left"
        case .right:
            return "right"
        case .topLeft:
            return "topLeft"
        case .topRight:
            return "topRight"
        case .bottomLeft:
            return "bottomLeft"
        case .bottomRight:
            return "bottomRight"
        @unknown default:
            return ""
        }
    }
}

extension UIView.ContentMode: Codable {
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.singleValueContainer()
        let string = try typeContainer.decode(String.self)
        guard let mode = UIView.ContentMode(rawValue: string) else {
            throw ContentModeError.notAContentMode
        }
        self = mode
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValueString)
    }
}
