//
//  UINavigationBar+Extension.swift
//  GSAE
//
//  Created by Mazy on 2018/5/30.
//  Copyright © 2018年 GSAE. All rights reserved.
//

import UIKit

extension UINavigationBar {
    
    /// 隐藏底部线
    func hideBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
        navigationBarImageView?.isHidden = true
        hideBottomBorder()
    }
    
    /// 显示底部线
    func showBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
        navigationBarImageView?.isHidden = true
        showBottomBorder()
    }
    
    /// 显示底部边界
    func showBottomBorder() {
        if let border = viewWithTag(123) {
            border.isHidden = false
        } else {
            let bottomBorderRect = CGRect(x: 0, y: frame.height, width: frame.width, height: 1 / UIScreen.main.scale)
            let bottomBorderView = UIView(frame: bottomBorderRect)
            bottomBorderView.tag = 123
            bottomBorderView.backgroundColor = UIColor(hexStr: "EAEAEA")
            addSubview(bottomBorderView)
        }
    }
    
    /// 隐藏底部边界
    func hideBottomBorder() {
        if let border = viewWithTag(123) {
            border.isHidden = true
        }
    }
    
    private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
        if let imageView = view as? UIImageView, view.bounds.height <= 1.0 {
            return imageView
        }
        
        for subview in view.subviews {
            if let imageView = hairlineImageViewInNavigationBar(view: subview) {
                return imageView
            }
        }
        return nil
    }
}
