//
//  YHHUDSquareBaseView.swift
//  PKHUD Demo
//
//  Created by ahao on 2018/4/19.
//  Copyright © 2018年 NSExceptional. All rights reserved.
//

import UIKit
import PKHUD

class YHHUDSquareBaseView: UIView {
    
    static let defaultSquareBaseViewFrame = CGRect(origin: CGPoint.zero, size: CGSize(width: 120, height: 120))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    init(image: UIImage? = nil, title: String? = nil) {
        super.init(frame: YHHUDSquareBaseView.defaultSquareBaseViewFrame)
        backgroundColor = UIColor.black
        imageView.image = image
        titleLabel.text = title
        titleLabel.sizeToFit()
        addSubview(containerView)
        containerView.addSubview(imageView)
        containerView.addSubview(titleLabel)
    }
    
    let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 14.0)
        label.textColor = UIColor.white
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.25
        return label
    }()
    
    let containerView: UIView = {
        let temp = UIView()
        return temp
    }()
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        
        let viewWidth = bounds.size.width
        let viewHeight = bounds.size.height
        
        let labelHeight = titleLabel.bounds.height
        let imageViewHeight: CGFloat = max(imageView.image?.size.height ?? 28, 30)
        let padding: CGFloat = labelHeight > 0 ? 8 : 0
        let containerWidth = viewWidth - 5 - 5
        let containerHeight = imageViewHeight + padding + labelHeight
        containerView.frame.size = CGSize(width: containerWidth, height: containerHeight)
        containerView.center = CGPoint(x: viewWidth/2.0, y: viewHeight/2.0)
        imageView.frame = CGRect(origin: CGPoint.zero,
                                 size: CGSize(width: containerWidth, height: imageViewHeight))
        titleLabel.frame = CGRect(origin: CGPoint(x: 0, y: imageView.frame.maxY + padding),
                                  size: CGSize(width: viewWidth-8, height: titleLabel.frame.height))
    }

}
