//
//  ActionViewController.swift
//  OpenInTusker
//
//  Created by Shadowfacts on 5/23/21.
//  Copyright © 2021 Shadowfacts. All rights reserved.
//

import UIKit
import MobileCoreServices

class ActionViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        findURLFromWebPage { (components) in
            if let components = components {
                self.searchForURLInApp(components)
            } else {
                self.findURLItem { (components) in
                    if let components = components {
                        self.searchForURLInApp(components)
                    }
                }
            }
        }
    }
    
    private func findURLFromWebPage(completion: @escaping (URLComponents?) -> Void) {
        for item in extensionContext!.inputItems as! [NSExtensionItem] {
            for provider in item.attachments! {
                guard provider.hasItemConformingToTypeIdentifier(kUTTypePropertyList as String) else {
                    continue
                }
                provider.loadItem(forTypeIdentifier: kUTTypePropertyList as String, options: nil) { (result, error) in
                    guard let result = result as? [String: Any],
                          let jsResult = result[NSExtensionJavaScriptPreprocessingResultsKey] as? [String: Any],
                          let urlString = jsResult["activityPubURL"] as? String ?? jsResult["url"] as? String,
                          let components = URLComponents(string: urlString) else {
                        completion(nil)
                        return
                    }
                    
                    completion(components)
                }
                return
            }
        }
        
        completion(nil)
    }
    
    private func findURLItem(completion: @escaping (URLComponents?) -> Void) {
        for item in extensionContext!.inputItems as! [NSExtensionItem] {
            for provider in item.attachments! {
                guard provider.hasItemConformingToTypeIdentifier(kUTTypeURL as String) else {
                    continue
                }
                provider.loadItem(forTypeIdentifier: kUTTypeURL as String, options: nil) { (result, error) in
                    guard let result = result as? URL,
                          let components = URLComponents(url: result, resolvingAgainstBaseURL: false) else {
                        completion(nil)
                        return
                    }
                    completion(components)
                }
                return
            }
        }
        
        completion(nil)
    }
    
    private func searchForURLInApp(_ components: URLComponents) {
        var components = components
        components.scheme = "tusker"
        self.openURL(components.url!)
        self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)
    }

    @objc private func openURL(_ url: URL) {
        var responder: UIResponder = self
        while let parent = responder.next {
            if let application = parent as? UIApplication {
                application.perform(#selector(openURL(_:)), with: url)
                break
            } else {
                responder = parent
            }
        }
    }
    
    @IBAction func done() {
        extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)
    }

}
