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

import UIKit
import CocoaLumberjack

struct AppInfo{
	let id: Int
	let title: String
    let urlOpener: URL
}

class ServicesTableViewCell: UITableViewCell {
	@IBOutlet weak var label: UILabel?
	@IBOutlet weak var icon: UIImageView?
}

class ServicesViewController: MiniPlayerEmbeddingViewController {
    // MARK: Private Properties/Types
    @IBOutlet private weak var tableView: UITableView!

	var appStoreHelpers: [StoreHelper] = []
    // To add new services with url openers the urls should be added to Info.plist LSApplicationQueriesSchemes key
    let apps = [AppInfo(id: 324684580, title: "Spotify", urlOpener: URL(string: "spotify:")!)]
}

extension ServicesViewController {
	override func viewDidLoad() {
        hasSearchButton = false
		super.viewDidLoad()
		title = NSLocalizedString("ONLINE MUSIC SERVICES", comment: "Services view title")

		var helpers = [StoreHelper] ()
		apps.forEach {
            helpers.append(StoreHelper(id: $0.id, urlOpener: $0.urlOpener))
		}
		appStoreHelpers = helpers

		// Accessibility
		tableView.makeAccessible(Accessibility.ThirdPartyServiceScreen.servicesList)

		tableView.reloadData()
	}
}

extension ServicesViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return appStoreHelpers.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ServicesTableViewCell", for: indexPath) as? ServicesTableViewCell ?? ServicesTableViewCell ()
		cell.label?.text = apps[indexPath.row].title // We set a default title in case offline.
		cell.makeAccessible(apps[indexPath.row].title, doNotLocalizeForHuman: true)

		appStoreHelpers[indexPath.row].appTitle(completion: { [weak self] title in
			guard
				let _ = self,
			 	let title = title else { return }
			cell.label?.text = title
			cell.makeAccessible(title, doNotLocalizeForHuman: true)
		})

		appStoreHelpers[indexPath.row].appImage(completion: { [weak self] image in
			guard let _ = self else { return }
			cell.icon?.image = image
		})

        // Configure the cell...

        return cell
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
		return CGFloat.leastNormalMagnitude
	}

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		tableView.deselectRow(at: indexPath, animated: true)

		appStoreHelpers[indexPath.row].appURL { url in
			if let url = url {
				UIApplication.shared.open(url,
										  options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]),
										  completionHandler: nil)
			}
		}
	}
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
	return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
