//
//  ViewController.swift
//  Project1
//
//  Created by Leonardo Bandeira on 13/05/21.
//

import UIKit

class ViewController: UITableViewController {
    
    // MARK: - Attributes
    
    var pictures = [String]()

    // MARK: - View Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()        
        
        navigationController?.navigationBar.prefersLargeTitles = true
        title = "Storm Viewer"
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareApp))
        
        performSelector(inBackground: #selector(loadNSSL), with: nil)
    }
    
    // MARK: - TableView
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return pictures.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
        let sortedPictures = pictures.sorted()
        
        cell.textLabel?.text = sortedPictures[indexPath.row]
        cell.textLabel?.font = UIFont(name: "Helvetica", size: 18)
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
            vc.selectedImage = pictures[indexPath.row]
            vc.arrayImages = [indexPath.row, pictures.count]

            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    // MARK: - Methods
    
    @objc func loadNSSL() {
        let fm = FileManager.default
        let path = Bundle.main.resourcePath!
        let items = try! fm.contentsOfDirectory(atPath: path)
        
        for item in items {
            if item.hasPrefix("nssl") {
                self.pictures.append(item)
            }
        }
        
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
    
    @objc func shareApp() {
        let textToShare = "Swift is awesome! See more in my GitHub!"

        if let myWebsite = NSURL(string: "https://github.com/leobandeiraf/storm-viewer/") {
            let objectsToShare: [Any] = [textToShare, myWebsite]
            let vc = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
            
            vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
            
            present(vc, animated: true)
        }
    }
}

