1*af2ec015STomasz Sapeta // Copyright 2021-present 650 Industries. All rights reserved.
2*af2ec015STomasz Sapeta 
3*af2ec015STomasz Sapeta import ABI49_0_0ExpoModulesCore
4*af2ec015STomasz Sapeta 
5*af2ec015STomasz Sapeta public final class KeepAwakeModule: Module {
6*af2ec015STomasz Sapeta   private var activeTags = Set<String>()
7*af2ec015STomasz Sapeta 
definitionnull8*af2ec015STomasz Sapeta   public func definition() -> ModuleDefinition {
9*af2ec015STomasz Sapeta     Name("ExpoKeepAwake")
10*af2ec015STomasz Sapeta 
11*af2ec015STomasz Sapeta     AsyncFunction("activate") { (tag: String) -> Bool in
12*af2ec015STomasz Sapeta       if self.activeTags.isEmpty {
13*af2ec015STomasz Sapeta         setActivated(true)
14*af2ec015STomasz Sapeta       }
15*af2ec015STomasz Sapeta       self.activeTags.insert(tag)
16*af2ec015STomasz Sapeta       return true
17*af2ec015STomasz Sapeta     }
18*af2ec015STomasz Sapeta 
19*af2ec015STomasz Sapeta     AsyncFunction("deactivate") { (tag: String) -> Bool in
20*af2ec015STomasz Sapeta       self.activeTags.remove(tag)
21*af2ec015STomasz Sapeta       if self.activeTags.isEmpty {
22*af2ec015STomasz Sapeta         setActivated(false)
23*af2ec015STomasz Sapeta       }
24*af2ec015STomasz Sapeta       return true
25*af2ec015STomasz Sapeta     }
26*af2ec015STomasz Sapeta 
27*af2ec015STomasz Sapeta     AsyncFunction("isActivated") { () -> Bool in
28*af2ec015STomasz Sapeta       return DispatchQueue.main.sync {
29*af2ec015STomasz Sapeta         return UIApplication.shared.isIdleTimerDisabled
30*af2ec015STomasz Sapeta       }
31*af2ec015STomasz Sapeta     }
32*af2ec015STomasz Sapeta 
33*af2ec015STomasz Sapeta     OnAppEntersForeground {
34*af2ec015STomasz Sapeta       if !self.activeTags.isEmpty {
35*af2ec015STomasz Sapeta         setActivated(true)
36*af2ec015STomasz Sapeta       }
37*af2ec015STomasz Sapeta     }
38*af2ec015STomasz Sapeta 
39*af2ec015STomasz Sapeta     OnAppEntersBackground {
40*af2ec015STomasz Sapeta       if !self.activeTags.isEmpty {
41*af2ec015STomasz Sapeta         setActivated(false)
42*af2ec015STomasz Sapeta       }
43*af2ec015STomasz Sapeta     }
44*af2ec015STomasz Sapeta   }
45*af2ec015STomasz Sapeta }
46*af2ec015STomasz Sapeta 
setActivatednull47*af2ec015STomasz Sapeta private func setActivated(_ activated: Bool) {
48*af2ec015STomasz Sapeta   DispatchQueue.main.async {
49*af2ec015STomasz Sapeta     UIApplication.shared.isIdleTimerDisabled = activated
50*af2ec015STomasz Sapeta   }
51*af2ec015STomasz Sapeta }
52