//
//  AdBlockView.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 06.07.18.
//  Copyright © 2018 Smaato Inc. All rights reserved.
//

import UIKit

@objc class AdBlockView: UIView {
    
    @objc public var tip: String? {
        set {
            tipLabel?.text = newValue
        }
        get {
            return tipLabel?.text
        }
    }
    
    private var backgroundLayer: CALayer?
    private var tipLabel: UILabel?
    
    enum AdBlockTextAlignment {
        case center
        case left
        
        func textAlignment() -> NSTextAlignment {
            switch self {
            case .center:
                return NSTextAlignment.center
            case .left:
                return NSTextAlignment.left
            }
        }
    }
    
    public var tipAlignment: AdBlockTextAlignment? {
        didSet {
            tipLabel?.textAlignment = tipAlignment?.textAlignment() ?? NSTextAlignment.center
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        customSetup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customSetup()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let size = self.frame.size
        backgroundLayer?.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    }
    
    //MARK: UI
    
    private func customSetup() {
        // Background
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor(red:0.83, green:0.83, blue:0.83, alpha:1).cgColor
        
        let gradient = CAGradientLayer()
        let size = self.frame.size
        gradient.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        gradient.colors = [
            UIColor(red:0.93, green:0.93, blue:0.93, alpha:1).cgColor,
            UIColor(red:0.89, green:0.89, blue:0.89, alpha:1).cgColor
        ]
        gradient.locations = [0, 1]
        gradient.startPoint = CGPoint(x: 0.5, y: 0)
        gradient.endPoint = CGPoint(x: 0.5, y: 1)
        self.layer.addSublayer(gradient)
        self.backgroundLayer = gradient
        
        // Tips label
        let label = UILabel(frame: self.bounds)
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.textAlignment = .center
        label.textColor = UIColor(red:0.62, green:0.62, blue:0.62, alpha:1)
        label.font = UIFont(appFont: .SFText_Italic, size: 13)
        label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        addSubview(label)
        self.tipLabel = label
    }
    
}
