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

import UIKit

class AVSCountrySelectionViewController: SettingsOptionsViewController {
    private var countryList = [String] ()
}

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

        super.viewDidLoad()

        // Accessibility
        tableView.makeAccessible(Accessibility.AVSCountrySelectionScreen.countryList)
    }
}

extension AVSCountrySelectionViewController: 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 countryName = countryList[index]
        return countryName == device.selectedAVSLocale
    }

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

        device.setSelectedAVSLocale(countryName,
                                    completion: nil,
                                    completionQueue: nil)
    }

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

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

    func loadOptions() {
        countryList = [String] ()
        guard
            let deviceID = deviceID,
            let device = playerController.device(id: deviceID)  else {
            	return
        }
		countryList = device.avsLocales
        if countryList.isEmpty {
            let currentCountry = device.selectedAVSLocale
            countryList = [currentCountry]
        }
    }
}
