//
//  Dictionary+.swift
//  YTBase_Example
//
//  Created by YouT on 2020/9/16.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import Foundation
import UIKit

public extension Dictionary {
    
    func stringForKey(_ key:Key) -> String {
        let theV = checkStringForKey(key) ? "\(self[key]!)" : ""
        if theV == "null" {
            return ""
        }else{
            return theV
        }
    }
    
    func doubleForKey(_ key:Key) -> Double {
        return self.stringForKey(key).doubleValue()
    }
    
    func intForKey(_ key:Key) -> Int {
        let intStr = stringForKey(key)
        return intStr.intValue()
    }
    
    func stringValue(forKey theKey:Key) -> String {
        if let theValue = self[theKey] {
            if let theStr = theValue as? String {
                return theStr
            }else{
                if theValue is NSNull {
                    return ""
                }else{
                    return "\(theValue)"
                }
            }
        }else{
            return ""
        }
    }
    
    func intValue(forKey theKey:Key) -> Int {
        let intStr = stringValue(forKey: theKey)
        return intStr.intValue()
    }
    
    func arrayValue(forKey theKey:Key) -> [[String:Any]] {
        if let theArr = self[theKey] as? [[String:Any]] {
            return theArr
        }else{
            return [[String:Any]]()
        }
    }
    
    func checkStringForKey(_ key:Key)->Bool {
        return self[key] != nil && !(self[key]! as AnyObject).isKind(of: NSNull.self) && "\(self[key]!)" != "" ? true : false
    }
    
    func checkValueFor(_ key:Key) -> Bool {
        return self[key] != nil && !(self[key]! is NSNull) ? true : false
    }
    
    
}

public extension NSDictionary {
    // 取字典内容的字符串，如果没有返回“”
    func stringValue(forKey theKey:String) -> String {
        if let theValue = self.object(forKey: theKey) {
            if let theStr = theValue as? String {
                return theStr
            }else{
                if theValue is NSNull {
                    return ""
                }else{
                    return "\(theValue)"
                }
            }
        }else{
            return ""
        }
    }
    
    // 取字典内容int，如果没有，返回0
    func intValue(forKey theKey:String) -> Int {
        let intStr = stringValue(forKey: theKey)
        return intStr.intValue()
    }
    
    // 取字典内容int，如果没有，返回0
    func floatValue(forKey theKey:String) -> CGFloat {
        let intStr = stringValue(forKey: theKey)
        return intStr.floatValue()
    }
    
}


//MARK:--- 重载运算符 两个字典合并为一个字典 ----------
public func += <key, value> ( _one: inout Dictionary<key, value>, _two: Dictionary<key, value>) {
    for (k, v) in _two {
        _one.updateValue(v, forKey: k)
    }
}
