<commit_before>//
//  This file is part of Blokada.
//
//  This Source Code Form is subject to the terms of the Mozilla Public
//  License, v. 2.0. If a copy of the MPL was not distributed with this
//  file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
//  Copyright © 2020 Blocka AB. All rights reserved.
//
//  @author <NAME>
//

import Foundation
import UIKit
import LocalAuthentication

class AccountViewModel: ObservableObject {

    @Published var account: Account?
    @Published var working: Bool = true
    @Published var showError: Bool = false

    var error: String? = nil {
        didSet {
            if error != nil {
                showError = true
            }
        }
    }

    var active: Bool {
        return account?.isActive() ?? false
    }

    var id: String {
        return account?.id ?? ""
    }

    var type: String {
        return Strings.accountType(account)
    }

    var activeUntil: String {
        return Strings.activeUntil(account)
    }

    private let log = Logger("Account")

    private let api = BlockaApiService.shared
    private let vpn = VpnService.shared

    init() {
        SharedActionsService.shared.newUser = newUser
        SharedActionsService.shared.updateAccount = updateAccount

        Config.shared.setOnAccountUpdated {
            self.syncConfig()
        }
    }

    init(mocked: String) {
        account = Account(id: mocked, active_until: "", active: false, type: "libre")
    }

    func openManageSubscriptions() {
        Links.openInBrowser(Links.manageSubscriptions())
    }

    func copyAccountIdToClipboard() {
        UIPasteboard.general.string = self.id
    }

    func restoreAccount(_ newId: AccountId, success: @escaping () -> Void) {
        self.log.v("Restore account")
        self.working = true

        onBackground {
            let accountId = newId.lowercased().trimmingCharacters(in: CharacterSet.whitespaces)
            self.api.getAccount(id: accountId) { error, account in onMain {
                guard error == nil else {
                    return self.onError(CommonError.accountInactiveAfterRestore, error)
                }

                guard /*!Env.isProduction ||*/ account!.isActive() else {
                    return self.onError(CommonError.accountInactiveAfterRestore)
                }

                self.vpn.turnOffEverything { _, _ in
                    self.log.v("Generating keypair after restoring account")
                    let (privateKey, publicKey) = self.vpn.generateKeypair()
                    Config.shared.newUser(
                        account: account!,
                        privateKey: privateKey,
                        publicKey: publicKey
                    )
                    self.setAccount(account!)

                    self.working = false
                    self.log.v("Restore account: done")
                    success()
                }
            }}
        }
    }

    private func syncConfig() {
        onMain {<commit_msg>not important<commit_after>//
//  This file is part of Blokada.
//
//  This Source Code Form is subject to the terms of the Mozilla Public
//  License, v. 2.0. If a copy of the MPL was not distributed with this
//  file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
//  Copyright © 2020 Blocka AB. All rights reserved.
//
//  @author <NAME>
//

import Foundation
import UIKit
import LocalAuthentication

class AccountViewModel: ObservableObject {

    @Published var account: Account?
    @Published var working: Bool = true
    @Published var showError: Bool = false

    var error: String? = nil {
        didSet {
            if error != nil {
                showError = true
            }
        }
    }

    var active: Bool {
        return account?.isActive() ?? false
    }

    var id: String {
        return account?.id ?? ""
    }

    var type: String {
        return Strings.accountType(account)
    }

    var activeUntil: String {
        return Strings.activeUntil(account)
    }

    private let log = Logger("Account")

    private let api = BlockaApiService.shared
    private let vpn = VpnService.shared

    init() {
        SharedActionsService.shared.newUser = newUser
        SharedActionsService.shared.updateAccount = updateAccount

        Config.shared.setOnAccountUpdated {
            self.syncConfig()
        }
    }

    init(mocked: String) {
        account = Account(id: mocked, active_until: "", active: false, type: "libre")
    }

    func openManageSubscriptions() {
        Links.openInBrowser(Links.manageSubscriptions())
    }

    func copyAccountIdToClipboard() {
        UIPasteboard.general.string = self.id
    }

    func restoreAccount(_ newId: AccountId, success: @escaping () -> Void) {
        self.log.v("Restore account")
        self.working = true

        onBackground {
            let accountId = newId.lowercased().trimmingCharacters(in: CharacterSet.whitespaces)
            self.api.getAccount(id: accountId) { error, account in onMain {
                guard error == nil else {
                    return self.onError(CommonError.accountInactiveAfterRestore, error)
                }

                guard !Env.isProduction || account!.isActive() else {
                    return self.onError(CommonError.accountInactiveAfterRestore)
                }

                self.vpn.turnOffEverything { _, _ in
                    self.log.v("Generating keypair after restoring account")
                    let (privateKey, publicKey) = self.vpn.generateKeypair()
                    Config.shared.newUser(
                        account: account!,
                        privateKey: privateKey,
                        publicKey: publicKey
                    )
                    self.setAccount(account!)

                    self.working = false
                    self.log.v("Restore account: done")
                    success()
                }
            }}
        }
    }

    private func syncConfig() {
        onMain {
{'fraction_non_alphanumeric': 0.09151193633952255, 'fraction_numerical': 0.002652519893899204, 'mean_word_length': 1.7447679708826205, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2750087', 'n_tokens_mistral': 1675, 'n_tokens_neox': 1540, 'n_words': 411}