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

import UIKit

class ModularAlertSoundSelectionViewController: SettingsOptionsViewController {
    private var soundList = [String] ()
}

extension ModularAlertSoundSelectionViewController {
    override func viewDidLoad() {
        source = self
        title = NSLocalizedString("ALERT SOUND", comment: "Alert Sound Title")

        super.viewDidLoad()

        // Accessibility
        tableView.makeAccessible(Accessibility.VoiceUIModularAlertSoundScreen.soundsList)
    }

    // Next two methods are to make auto layout magic work by resizing the header height to fit the text with
    // appropriate margins.
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        sizeHeaderToFit()
    }

    func sizeHeaderToFit() {
        let headerView = tableView.tableHeaderView!

        headerView.setNeedsLayout()
        headerView.layoutIfNeeded()

        let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height

        var frame = headerView.frame
        let oldHeight = frame.size.height

        if abs(oldHeight-height) > 0.01 {
            // We only update if it's changed otherwise we enter infinite loop
            frame.size.height = height
            headerView.frame = frame
            tableView.tableHeaderView = headerView
        }
    }
}

extension ModularAlertSoundSelectionViewController: 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 soundName = soundList[index]
        return soundName == device.modularClientAlertFile
    }

    func itemSelected(at index: Int) {
        let soundName = soundList[index]
        guard
            let deviceID = deviceID,
            let device = playerController.device(id: deviceID),
            soundName != device.modularClientAlertFile else {
                return
        }
       device.setModularClientAlertFile(soundName,
                                        completion: nil,
                                        completionQueue: nil)
    }

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

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

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

        let currentSound = device.modularClientAlertFile
        soundList = [currentSound]
    }
}
