//
//  MasterViewController.swift
//  JSONCreator
//
//  Created by Scott Pfeil on 8/2/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import UIKit

struct Section {
    var name: String
    var paths: [String] = []
    mutating func addPath(path: String){
        paths.append(path)
    }
    mutating func sort() {
        paths = paths.sorted{ $0 < $1 }
    }
}

class MasterViewController: UITableViewController {

    let folderPath = Bundle.main.resourcePath! + "/JSON"
    var sections: [Section] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // setup the data
        let sectionNames = try! FileManager.default.contentsOfDirectory(atPath: folderPath).sorted { $0 < $1 }
        for sectionName in sectionNames {
            var section = Section(name: sectionName)
            let paths = try! FileManager.default.subpathsOfDirectory(atPath: "\(folderPath)/\(sectionName)")
            for path in paths {
                if path.hasSuffix(".json") {
                    section.addPath(path: path)
                }
            }
            section.sort()
            sections.append(section)
        }
    }
    
    func getData(for indexPath: IndexPath) -> String? {
        let section = sections[indexPath.section]
        let path = "\(folderPath)/\(section.name)/\(section.paths[indexPath.row])"
        return try! String.init(contentsOfFile: path)
    }

    // MARK: - Table View
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].name
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].paths.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = sections[indexPath.section].paths[indexPath.row]
        if cell.interactions.first == nil {
            let dragInteraction = UIDragInteraction(delegate: self)
            cell.addInteraction(dragInteraction)
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UIPasteboard.general.string = getData(for: indexPath)
        
        let label = UILabel(frame: .zero)
        label.clipsToBounds = true
        label.backgroundColor = .gray
        label.text = "   Copied   "
        label.font = UIFont.systemFont(ofSize: 40)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.layer.cornerRadius = 5
        view.superview!.addSubview(label)
        label.centerXAnchor.constraint(equalTo: view.superview!.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.superview!.centerYAnchor).isActive = true
        UIView.animate(withDuration: 2, animations: {
            label.alpha = 0
        }) { (completed) in
            label.removeFromSuperview()
        }
    }
}

extension MasterViewController: UIDragInteractionDelegate {
    func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
        let location = session.location(in: tableView)
        let indexPath = tableView.indexPathForRow(at: location)
        let content = getData(for: indexPath!)
        let provider = NSItemProvider(object: content! as NSString)
        let item = UIDragItem(itemProvider: provider)
        return [item]
    }
}
