import Foundation
import Capacitor
import ReplayKit
import UIKit

/**
 * Please read the Capacitor iOS Plugin Development Guide
 * here: https://capacitorjs.com/docs/plugins/ios
 */
@objc(TestPlugin)
public class TestPlugin: CAPPlugin {

    @objc func echo(_ call: CAPPluginCall) {
        let value = call.getString("value") ?? ""
        call.success([
            "value": value
        ])
    }

    @objc func start(_ call: CAPPluginCall) {
        let recorder = RPScreenRecorder.shared()

                recorder.startRecording{ [unowned self] (error) in
                    if let unwrappedError = error {
                        print(unwrappedError.localizedDescription)
                    } else {
                        
                    }
                }
       
        call.success([
            "status": true
        ])
    }
    
    @objc func stop(_ call: CAPPluginCall) {
         print("Stopped recording is called")
        let recorder = RPScreenRecorder.shared()
        recorder.stopRecording { [unowned self] (preview, error) in
                    print("Stopped recording")

                    let alert = UIAlertController(
                            title: "Recording Finished",
                            message: "Would you like to edit or delete your recording?",
                            preferredStyle: .alert
                    )

                    let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action: UIAlertAction) in
                        recorder.discardRecording(handler: { () -> Void in
                            print("Recording successfully deleted.")
                        })
                    })

                    let editAction = UIAlertAction(title: "Edit", style: .default, handler: { (action: UIAlertAction) -> Void in
                        
                        self.bridge.viewController.present(preview!, animated: true, completion: nil)
                    })

                    alert.addAction(editAction)
                    alert.addAction(deleteAction)
                    self.bridge.viewController.present(alert, animated: true, completion: nil)

                }
                call.success([
                "status": true,
                "desc": "stope recording"
                    ])
        }
}
