//
// © 2018-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import UIKit

class ModularLanguageSelectionViewController: SettingsOptionsViewController {
    private var languageList = [String] ()
}

extension ModularLanguageSelectionViewController {
    override func viewDidLoad() {
        source = self
        title = NSLocalizedString("LANGUAGE", comment: "Country Title")

        super.viewDidLoad()

        // Accessibility
        tableView.makeAccessible(Accessibility.VoiceUIModularLanguageScreen.languagesList)
    }
}

extension ModularLanguageSelectionViewController: SettingsOptionsSource {
    func requiredObservers() -> [SettingsOptionsRequiredObservers] {
        return [.device, .voiceUI]
    }

    func isCurrentSelection(at index: Int) -> Bool {
        guard
            let deviceID = deviceID,
            let device = playerController.device(id: deviceID) else {
                return false
        }

        let languageName = languageList[index]
        return languageName == device.selectedModularClientLanguage
    }

    func itemSelected(at index: Int) {
        let languageName = languageList[index]
        guard
            let deviceID = deviceID,
            let device = playerController.device(id: deviceID),
            languageName != device.selectedModularClientLanguage else {
                return
        }

        device.setSelectedModularClientLanguage(languageName,
                                                completion: nil,
                                                completionQueue: nil)
    }

    func item(at index: Int) -> SettingsOptionsSourceItem {
        return SettingsOptionsSourceItem(cellTitle: languageList[index],
                                         unlocalizedAccessibilityTitle: languageList[index])
    }

    func numberOfItems() -> Int {
        return languageList.count
    }

    func loadOptions() {
        guard
            let deviceID = deviceID,
            let device = playerController.device(id: deviceID) else {
                languageList = [String] ()
                return
        }

        languageList = device.modularClientLanguages
    }
}
