//
/*
 * Copyright (c) 2021 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


/// Helper  class for making our SwiftUI view available to ObjectiveC
@objcMembers class DeveloperSettingsViewController: NSObject {

    @available(iOS 14.0, *)
    class func makeViewController(session: MXSession) -> UIViewController {
        return UIHostingController(rootView: DeveloperSettingsView(session: session))
    }
}

// MARK: -

struct DeveloperSettingsView: View {
    let session: MXSession?
    
    @State private var showAlert = false
    @State private var showAlertBirthdayCampaign = false
    @State private var permalinkPrefix: String? = UserDefaults.standard.string(forKey: "bwi_permalink_prefix")
    
    var body: some View {
        Form {
            SwiftUI.Section {
                Button(action: { showAlert = createNewPersonalNotesRoom(mxSession: session) }) {
                    Text(BWIL10n.bwiSettingsDeveloperCreateNewPersonalNotesRoom)
                        .foregroundColor(Color(ThemeService.shared().theme.tintColor))
                        .font(.system(size: 17))
                }
                .alert(isPresented: $showAlert) {
                    Alert(title: Text(BWIL10n.bwiSettingsDeveloper), dismissButton: .default(Text("Ok")))
                }
                
                Button(action:  { showAlert = resetMatomoInfoScreen(mxSession: session) }) {
                    Text(BWIL10n.bwiSettingsDeveloperResetMatomoInfo)
                        .foregroundColor(Color(ThemeService.shared().theme.tintColor))
                        .font(.system(size: 17))
                }
                .alert(isPresented: $showAlert) {
                    Alert(title: Text(BWIL10n.bwiSettingsDeveloperShowMatomoPrivacyNotesResetted), message: Text(BWIL10n.bwiSettingsDeveloperShowMatomoPrivacyNotesResetted), dismissButton: .default(Text("Ok")))
                }
                Button(action:  { showAlertBirthdayCampaign = resetBirthdayCampaignScreen(mxSession: session) }) {
                    Text(BWIL10n.bwiSettingsDeveloperSettingsResetBirthdayBanner)
                        .foregroundColor(Color(ThemeService.shared().theme.tintColor))
                        .font(.system(size: 17))
                }
                .alert(isPresented: $showAlertBirthdayCampaign) {
                    Alert(title: Text(BWIL10n.bwiSettingsDeveloperSettingsBirthdayBannerResettetTitle), message: Text(BWIL10n.bwiSettingsDeveloperSettingsBirthdayBannerResettetMessage), dismissButton: .default(Text("Ok")))
                }
                Button(action:  { _ = restrictUser(mxSession: session) }) {
                    Text(BWIL10n.bwiSettingsDeveloperRestrictUser)
                        .foregroundColor(Color(ThemeService.shared().theme.tintColor))
                        .font(.system(size: 17))
                }
                Button(action:  { _ = unrestrictUser(mxSession: session) }) {
                    Text(BWIL10n.bwiSettingsDeveloperUnrestrictUser)
                        .foregroundColor(Color(ThemeService.shared().theme.tintColor))
                        .font(.system(size: 17))
                }
                Button(action:  { _ = unmarkBannerVersion(mxSession: session) }) {
                    Text(BWIL10n.bwiSettingsDeveloperUnmarkBanner)
                        .foregroundColor(Color(ThemeService.shared().theme.tintColor))
                        .font(.system(size: 17))
                }
            }
            if BWIBuildSettings.shared.permalinkPrefixSettings && !BWIBuildSettings.shared.permalinkPrefixes.isEmpty {
                SwiftUI.Section(header: Text(BWIL10n.settingsPermalinkPrefixPickerTitle)) {
                    Picker("", selection: $permalinkPrefix) {
                        ForEach(BWIBuildSettings.shared.permalinkPrefixes, id: \.self) { prefix in
                            Text(prefix)
                                .tag(String?.some(prefix))
                        }
                    }
                    .id(UUID())
                    .onChange(of: permalinkPrefix) { newValue in
                        UserDefaults.standard.set(newValue, forKey: "bwi_permalink_prefix")
                    }
                }
            }
            SwiftUI.Section {
                NavigationLink {
                    WellKnownView(session: session)
                } label: {
                    Text(BWIL10n.bwiSettingsDeveloperWellKnown)
                }
                NavigationLink {
                    ServerCapabilitiesView(session: session)
                } label: {
                    Text(BWIL10n.bwiSettingsDeveloperCapabilities)
                }
                NavigationLink {
                    MaintenanceView(session: session)
                } label: {
                    Text(BWIL10n.bwiSettingsDeveloperMaintenance)
                }
                NavigationLink {
                    UserAccountDataView(session: session)
                } label: {
                    Text(BWIL10n.bwiSettingsDeveloperUserAccountData)
                }
                NavigationLink {
                    ServerSideKeyBackupView(session: session)
                } label: {
                    Text(BWIL10n.bwiSettingsDeveloperKeyBackup)
                }
            }
        }
        .listStyle(.grouped)
        .navigationTitle(BWIL10n.bwiSettingsDeveloper)
        .navigationBarTitleDisplayMode(.inline)
    }

}

@available(iOS 14.0, *)
struct DeveloperSettingsView_Previews: PreviewProvider {
    static var previews: some View {
        DeveloperSettingsView(session: nil)
    }
}

// MARK: - Button Actions

fileprivate func createNewPersonalNotesRoom(mxSession: MXSession?) -> Bool {
    guard let mxSession = mxSession else {
        return false
    }

    let service = PersonalNotesDefaultService(mxSession: mxSession)
    service.resetPersonalNotesRoom()
    service.createPersonalNotesRoomIfNeeded()
    return true
}

fileprivate func resetMatomoInfoScreen(mxSession: MXSession?) -> Bool {
    guard let mxSession = mxSession else {
        return false
    }
    BWIAnalyticsAccountDataService(mxSession: mxSession)
    return true
}

fileprivate func resetBirthdayCampaignScreen(mxSession: MXSession?) -> Bool {
    guard let mxSession = mxSession else {
        return false
    }
    let sharedSettings = RiotSharedSettings(session: mxSession)
    let campaign = BWIBuildSettings.shared.bwiHappyBirthdayCampaignIdentifier
    sharedSettings.setHappyBirthdayCampaign(campaign, enabled: true) {
    } failure: { error in
        if let error = error {
            MXLog.debug("[HappyBirthdayCampaign] could not set flag in account data. Error: \(error)")
        }
    }

    return true
}

fileprivate func restrictUser(mxSession: MXSession?) -> Bool {
    guard let mxSession = mxSession else {
        return false
    }
    AccountRestrictionService(mxSession: mxSession).updateRestriction(roomAccess: true, addressListAccess: true)
    
    return true
}

fileprivate func unrestrictUser(mxSession: MXSession?) -> Bool {
    guard let mxSession = mxSession else {
        return false
    }
    AccountRestrictionService(mxSession: mxSession).updateRestriction(roomAccess: false, addressListAccess: false)
    return true
}

fileprivate func unmarkBannerVersion(mxSession: MXSession?) -> Bool {
    guard let mxSession = mxSession else {
        return false
    }
    
    //     NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
        _ = FeatureBannerVisibilityService(mxSession: mxSession).markAsUnread(version: version)
    }

    return true
}
