//
//  UserModelResponse.swift
//  WoWonder
//
//  Created by Mohammed Hamad on 08/08/2022.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import Foundation
import UIKit

struct UserModelResponse: Codable {
    
    let api_status : Int?
    let data : [UserData]?
    let video_call : Bool?
    let video_call_user : UserCallUnion?
    let audio_call : Bool?
    let audio_call_user : UserCallUnion?
    let agora_call : Bool?
    let agora_call_data : UserCallUnion?
    
    enum CodingKeys: String, CodingKey {
        case api_status = "api_status"
        case data = "data"
        case video_call = "video_call"
        case video_call_user = "video_call_user"
        case audio_call = "audio_call"
        case audio_call_user = "audio_call_user"
        case agora_call = "agora_call"
        case agora_call_data = "agora_call_data"
    }
    
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        api_status = try values.decodeIfPresent(Int.self, forKey: .api_status)
        data = try values.decodeIfPresent([UserData].self, forKey: .data)
        video_call = try values.decodeIfPresent(Bool.self, forKey: .video_call)
        video_call_user = try values.decodeIfPresent(UserCallUnion.self, forKey: .video_call_user)
        audio_call = try values.decodeIfPresent(Bool.self, forKey: .audio_call)
        audio_call_user = try values.decodeIfPresent(UserCallUnion.self, forKey: .audio_call_user)
        agora_call = try values.decodeIfPresent(Bool.self, forKey: .agora_call)
        agora_call_data = try values.decodeIfPresent(UserCallUnion.self, forKey: .agora_call_data)
    }
    
}

enum UserCallUnion: Codable {
    
    case anythingArray([JSONAny])
    case userCallData(UserCallData)
    
    var userCallValue: UserCallData? {
        switch self {
        case let .anythingArray(value):
            print(value)
            return nil
        case let .userCallData(value):
            return value
        }
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode([JSONAny].self) {
            self = .anythingArray(x)
            return
        }
        if let x = try? container.decode(UserCallData.self) {
            self = .userCallData(x)
            return
        }
        throw DecodingError.typeMismatch(UserCallUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ChannelsUnion"))
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .anythingArray(let x):
            try container.encode(x)
        case .userCallData(let x):
            try container.encode(x)
        }
    }
}
