/*
 * Copyright (c) 2022 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import SwiftUI

@available(iOS 14.0, *)
/// The splash screen shown at the beginning of the onboarding flow.
struct OnboardingBwiSplashScreen: View {

    // MARK: - Properties
    
    // MARK: Private
    
    @Environment(\.theme) private var theme
    @Environment(\.layoutDirection) private var layoutDirection
    
    /// The dimensions of the stack with the action buttons and page indicator.
    @State private var overlayFrame: CGRect = .zero
    @State private var isFetchingDowntime = false
    @State private var showAlert = false
    @State private var activeAlert: ServerMaintenanceAlertType = .showInvalidAppVersionAlert

    // MARK: Public
    
    @ObservedObject var viewModel: OnboardingBwiSplashScreenViewModel.Context
    
    /// The main action buttons.
    var startButton: some View {
        Button(action: startButtonAction) {
            if isFetchingDowntime {
                ProgressView()
            } else {
                Text(BWIL10n.splashScreenStart)
                    .font(theme.fonts.body.bold())
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 32)
            }
        }
            .foregroundColor(.white)
            .background(theme.colors.accent)
            .cornerRadius(5)
            .padding([.leading, .trailing], 20)
    }
    
    var footer: some View {
        Image("powered_by_BWI_blk")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 140, alignment: .center)
    }
    
    var body: some View {
        ZStack {
            VStack(spacing: 30) {
                startButton
                    .padding()
                Spacer()
                footer
                    .padding()
            }
        }
        .navigationTitle("")
        .navigationBarHidden(true)
        .alert(isPresented: $showAlert, content: {
            ServerDowntimeDefaultService.shared.alert(alertType: activeAlert) {
                viewModel.send(viewAction: .login)
            }
        })
    }
    
    private func startButtonAction() {
        if BWIBuildSettings.shared.enableMaintenanceInfoOnLogin {
            isFetchingDowntime = true   // show progresview
            
            if BWIBuildSettings.shared.useTestDataForDowntime {
                ServerDowntimeDefaultService.shared.fetchDowntimes {
                    self.isFetchingDowntime = false // hide progressview
                    self.showAlertIfNeeded()
                }
            } else {
                ServerDowntimeDefaultService.shared.fetchDowntimesWithDirectRequest { success, _, _, _ in
                    DispatchQueue.main.async {
                        self.isFetchingDowntime = false   // hide progressview
                        if success {
                            self.showAlertIfNeeded()
                        } else {
                            showAlert = true
                            activeAlert = .showServerMaintenanceDefaultAlert
                        }
                    }
                }
            }
        } else {
            viewModel.send(viewAction: .login)
        }
    }
    
    
    private func showAlertIfNeeded() {
        if ServerDowntimeDefaultService.shared.showAlert() {
            activeAlert = ServerDowntimeDefaultService.shared.alertType()
            showAlert = true
        } else {
            viewModel.send(viewAction: .login)
        }
    }
}

// MARK: - Previews

@available(iOS 14.0, *)
struct OnboardingBwiSplashScreen_Previews: PreviewProvider {
    static let stateRenderer = MockOnboardingBwiSplashScreenScreenState.stateRenderer
    static var previews: some View {
        stateRenderer.screenGroup()
    }
}
