// 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 http://mozilla.org/MPL/2.0/.

import UIKit

protocol ChangeAppThemeControllerDelegate: class {
    func changeAppThemeControllerDidChange(_ controller: ChangeAppThemeController)
}

class ChangeAppThemeController: StaticTableController {
    weak var delegate: ChangeAppThemeControllerDelegate?

    fileprivate let userDefaults: UserDefaultsManager
    fileprivate let selectedStatus: UserDefaultsManager.AppTheme

    fileprivate let themeAutomatic = StaticTableDefaultCellModel()
    fileprivate let themeLight = StaticTableDefaultCellModel()
    fileprivate let themeDark = StaticTableDefaultCellModel()

    init(theme: Theme) {
        self.userDefaults = UserDefaultsManager()
        self.selectedStatus = userDefaults.appTheme

        super.init(theme: theme, style: .plain, model: [
            [themeAutomatic],
                [themeLight],
                [themeDark],
        ], footers: [
                String(localized: "settings_theme_automatic_notice"),
        nil,
        nil]
        )

        updateModels()

        title = String(localized: "settings_theme_title")
    }

    required convenience init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private extension ChangeAppThemeController {
    func updateModels() {
        themeAutomatic.value = String(localized: "settings_theme_automatic")
        themeAutomatic.didSelectHandler = changeThemeAutomatic

        themeLight.value = String(localized: "settings_theme_light")
        themeLight.didSelectHandler = changeThemeLight

        themeDark.value = String(localized: "settings_theme_dark")
        themeDark.didSelectHandler = changeThemeDark

        switch selectedStatus {
            case .themeAutomatic:
                themeAutomatic.rightImageType = .checkmark
            case .themeLight:
                themeLight.rightImageType = .checkmark
            case .themeDark:
                themeDark.rightImageType = .checkmark
        }
    }

    func changeThemeAutomatic(_: StaticTableBaseCell) {
        userDefaults.appTheme = .themeAutomatic
        delegate?.changeAppThemeControllerDidChange(self)
    }

    func changeThemeLight(_: StaticTableBaseCell) {
        userDefaults.appTheme = .themeLight
        delegate?.changeAppThemeControllerDidChange(self)
    }

    func changeThemeDark(_: StaticTableBaseCell) {
        userDefaults.appTheme = .themeDark
        delegate?.changeAppThemeControllerDidChange(self)
    }
}
