//
//  ScreenBrightnessModifierBehavior.swift
//  MVMCoreUI
//
//  Created by Kyle on 5/9/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

public class ScreenBrightnessModifierBehaviorModel: PageBehaviorModelProtocol {
    public var shouldAllowMultipleInstances: Bool = false
    public static var identifier = "screenBrightnessModifier"
    @Clamping(range: 0...1) var screenBrightness: CGFloat
    var originalScreenBrightness: CGFloat?
    
    //MARK:- Codable

    private enum CodingKeys: String, CodingKey {
        case screenBrightness
    }
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        screenBrightness = try typeContainer.decode(CGFloat.self, forKey: .screenBrightness)
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(screenBrightness, forKey: .screenBrightness)
    }
}

public class ScreenBrightnessModifierBehavior: PageVisibilityBehavior {
    var model: PageBehaviorModelProtocol
    
    required public init(model: PageBehaviorModelProtocol, delegateObject: MVMCoreUIDelegateObject?) {
        self.model = model
    }
    
    //MARK:- PageVisibilityBehavior
    
    public func onPageShown(_ delegateObject: MVMCoreUIDelegateObject?) {
        changeScreenBrightness()
    }
    
    public func onPageHidden(_ delegateObject: MVMCoreUIDelegateObject?) {
        restoreScreenBrightness()
    }
    
    //MARK:- Behavior
    
    func changeScreenBrightness() {
        guard let model = model as? ScreenBrightnessModifierBehaviorModel,
              model.originalScreenBrightness == nil else { return }
        model.originalScreenBrightness = UIScreen.main.brightness
        UIScreen.main.brightness = model.screenBrightness
        NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
    }
    
    func restoreScreenBrightness() {
        guard let model = model as? ScreenBrightnessModifierBehaviorModel,
              let originalScreenBrightness = model.originalScreenBrightness else { return }
        UIScreen.main.brightness = originalScreenBrightness
        model.originalScreenBrightness = nil
        NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
    }
    
    @objc func willResignActive() {
        restoreScreenBrightness()
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    @objc func didBecomeActive() {
        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
        changeScreenBrightness()
    }
}
