import ALCameraViewController

@objc(MobitorCameraSwift) class MobitorCameraSwift : CDVPlugin {
    func takePhoto(_ command: CDVInvokedUrlCommand) {
        var pluginResult = CDVPluginResult(
            status: CDVCommandStatus_ERROR
        )
        
        let msg = command.arguments[0] as? String ?? ""
        
        if msg.count > 0 {
            
            let maxPhotoScale = 1.0 // TODO: use parameter
            let croppingParams = CroppingParameters(isEnabled: false, allowResizing: false, allowMoving: false, minimumSize: CGSize.init(width: 1.0, height: 1.0))
            let cameraViewController = CameraViewController(scaleFactor: CGFloat(maxPhotoScale), croppingParameters: croppingParams, allowsLibraryAccess: false, allowsSwapCameraOrientation: true, allowVolumeButtonCapture: true, completion: { [weak self] (imageData, img, nil, errorData, exifData) in
                
                if let errorData = errorData {
                    pluginResult = CDVPluginResult.init(status: CDVCommandStatus_ERROR, messageAs: errorData)
                }
                if let _ = img, let imageData = imageData {
                    if let exifData = exifData {
                        pluginResult = CDVPluginResult.init(status: CDVCommandStatus_OK, messageAs: exifData)
                    }
                    
                    let base64Data = imageData.base64EncodedData(options: NSData.Base64EncodingOptions.endLineWithLineFeed)
                    pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: String(data: base64Data, encoding: .utf8))
                    
                    self?.commandDelegate!.send(
                        pluginResult,
                        callbackId: command.callbackId
                    )
                    
                } else {
                    
                    if let exifData = exifData {
                        pluginResult = CDVPluginResult.init(status: CDVCommandStatus_ERROR, messageAs: exifData)
                    } else {
                        pluginResult = CDVPluginResult.init(status: CDVCommandStatus_ERROR, messageAs: "nil")
                    }
                    
                    self?.commandDelegate!.send(
                        pluginResult,
                        callbackId: command.callbackId
                    )
                }
                
                self?.viewController.dismiss(animated: true, completion: nil)
            })
            
            self.viewController?.present(
                cameraViewController,
                animated: true,
                completion: nil
            )
            
        }
    }
}
