//
//  ConsentViewController.swift
//  RK-Journals
//
//  Created by Juan David Lopez Regalado on 11/11/24.
//

import UIKit
import ResearchKitUI

class ConsentViewController: UIViewController, ORKTaskViewControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    @IBAction func joinButtonTapped(_ sender: UIButton) {
        let taskViewController = ORKTaskViewController(task: ConsentTask, taskRun: nil)
        taskViewController.delegate = self
        taskViewController.modalPresentationStyle = .fullScreen
        present(taskViewController, animated: true, completion: nil)
    }
    
    func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskFinishReason, error: Error?) {
        
        switch reason {
        case .completed:
            // Obtener el resultado de la firma
            guard let signatureResult = taskViewController.result.stepResult(forStepIdentifier: "ConsentReviewStep")?.firstResult as? ORKConsentSignatureResult else {
                print("No se pudo obtener el resultado de la firma.")
                return
            }
            
            // Crear una copia del documento de consentimiento
            let consentDocument = ConsentDocument.copy() as! ORKConsentDocument
            signatureResult.apply(to: consentDocument)
            
            // Generar el PDF
            consentDocument.makePDF { (data, error) in
                if let error = error {
                    print("Error al crear PDF: \(error.localizedDescription)")
                    return
                }
                
                guard let data = data else {
                    print("No se generó ningún dato para el PDF.")
                    return
                }
                
                // Guardar el PDF en el directorio de documentos
                do {
                    var docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
                    docURL = docURL?.appendingPathComponent("consent.pdf")
                    try data.write(to: docURL!, options: .atomicWrite)
                    print("PDF guardado en: \(docURL!.path)")
                } catch {
                    print("Error al guardar el PDF: \(error.localizedDescription)")
                }
            }
            
            // Realizar la transición al siguiente controlador
            performSegue(withIdentifier: "unwindToTasks", sender: nil)
            
        case .discarded, .failed, .saved:
            dismiss(animated: true, completion: nil)

        case .earlyTermination:
            dismiss(animated: true, completion: nil)

        @unknown default:
            // Manejar casos no contemplados
            dismiss(animated: true, completion: nil)
        }
    }



}


