//
//  AppDelegate.swift
//  Feels (iOS)
//
//  Created by Trey Tartt on 1/10/22.
//

import Foundation
import UserNotifications
import UIKit
import WidgetKit
import SwiftUI
import Firebase

class AppDelegate: NSObject, UIApplicationDelegate {
    private let savedOnboardingData = UserDefaultsStore.getOnboarding()
    @AppStorage(UserDefaultsStore.Keys.textColor.rawValue, store: GroupUserDefaults.groupDefaults) private var textColor: Color = DefaultTextColor.textColor

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
//        PersistenceController.shared.clearDB()
//        PersistenceController.shared.deleteLast(numberOfEntries: 5)
//        GroupUserDefaults.groupDefaults.set(false, forKey: UserDefaultsStore.Keys.showNSFW.rawValue)
        
        FirebaseApp.configure()
        PersistenceController.shared.removeNoForDates()
        PersistenceController.shared.fillInMissingDates()
        UNUserNotificationCenter.current().delegate = self
        
        UIPageControl.appearance().currentPageIndicatorTintColor = UIColor(textColor)
        UIPageControl.appearance().pageIndicatorTintColor = UIColor.systemGray
        
        let appearance = UITabBarAppearance()
        appearance.configureWithOpaqueBackground()
        UITabBar.appearance().standardAppearance = appearance
        UITabBar.appearance().scrollEdgeAppearance = appearance
        
        EventLogger.log(event: "app_launced")
        
        return true
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        PersistenceController.shared.fillInMissingDates()
        
        // reschedule notifications so there's a new title next notification
        LocalNotification.rescheduleNotifiations()
        
        EventLogger.log(event: "app_foregorund")
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    func requestAuthorization() {  }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.badge, .banner, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if let action = LocalNotification.ActionType(rawValue: response.actionIdentifier) {
            var date: Date
            
            switch savedOnboardingData.inputDay {
            case .Today:
                date = Date()
            case .Previous:
                date = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
            }
            
            
            switch action {
            case .horrible:
                PersistenceController.shared.add(mood: .horrible, forDate: date, entryType: .notification)
            case .bad:
                PersistenceController.shared.add(mood: .bad, forDate: date, entryType: .notification)
            case .average:
                PersistenceController.shared.add(mood: .average, forDate: date, entryType: .notification)
            case .good:
                PersistenceController.shared.add(mood: .good, forDate: date, entryType: .notification)
            case .great:
                PersistenceController.shared.add(mood: .great, forDate: date, entryType: .notification)
            }
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        WidgetCenter.shared.reloadAllTimelines()
        completionHandler()
    }
}
