import { findComponentsByKeyValue } from "./helpers";

export const videoRecorderXML = () => {
  return `
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.camera.view.PreviewView
            android:id="@+id/camera_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/_40sdp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="Record Button" />

    </RelativeLayout>
    `;
};

export const videoRecorderFragmentFunctions = (fragment) => {
  if (findComponentsByKeyValue(fragment, "name", "VideoView").length == 0)
    return "";

  return `
  @SuppressLint("RestrictedApi", "NewApi")
    private fun init() {
//        val intent = intent
        cameraProviderListenableFuture = ProcessCameraProvider.getInstance(requireActivity())
        cameraProviderListenableFuture!!.addListener({
            try {
                val cameraProvider = cameraProviderListenableFuture!!.get()
                //  startCameraX(cameraProvider);
                cameraProvider.unbindAll()
                val selector =
                    CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK)
                        .build()
                val preview = Preview.Builder().build()
                preview.setSurfaceProvider(binding!!.cameraView.surfaceProvider)
                videoCapture = VideoCapture.Builder().setVideoFrameRate(30).build()
                cameraProvider.bindToLifecycle(
                    (this as LifecycleOwner),
                    selector,
                    preview,
                    videoCapture
                )
            } catch (e: Exception) {
                //AppLogger.log("Exception", "Exception " + e.message)
            }
        }, executor)
        binding!!.btnStop.setOnClickListener {
            if (!startedRecording) {
                startVideoRecording()
                countDownTimer = object : CountDownTimer((60000 * 3).toLong(), 1) {
                    @SuppressLint("SetTextI18n")
                    override fun onTick(millisUntilFinished: Long) {
                        val f: NumberFormat = DecimalFormat("00")
                        val min = millisUntilFinished / 60000 % 60
                        val sec = millisUntilFinished / 1000 % 60
                        //binding!!.tvTimer.text = f.format(min) + ":" + f.format(sec)
                    }

                    override fun onFinish() {
                        stopVideoRecording()
                    }
                }.start()
                //Toaster.toast("Recording started")
                binding!!.btnStop.setText("Stop Button")
            } else {
                stopVideoRecording()
                countDownTimer!!.cancel()
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    @SuppressLint("RestrictedApi", "MissingPermission")
    private fun startVideoRecording() {
        if (videoCapture != null) {
            val path = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .toString() + File.separator + "RedEyed_videos"
            )
            if (!path.exists()) {
                path.mkdir()
            }
            val date = Date()
            val timsStamp = date.time.toString()
            val fileName = "redeye-$timsStamp.mp4"
            val vidFile = File(path, fileName)
            startedRecording = true
            videoCapture!!.startRecording(
                VideoCapture.OutputFileOptions.Builder(vidFile).build(),
                executor,
                object : VideoCapture.OnVideoSavedCallback {
                    override fun onVideoSaved(outputFileResults: VideoCapture.OutputFileResults) {
                        openUploadVideoActivity(Uri.parse(vidFile.toString()))
                    }

                    override fun onError(
                        videoCaptureError: Int,
                        message: String,
                        cause: Throwable?
                    ) {
                        //Toaster.toast("Video not Saved " + message + " " + cause!!.message)
                        //AppLogger.log("Video not Saved ", message + " " + cause.message)
                    }
                })
        }
    }

    @SuppressLint("RestrictedApi")
    private fun stopVideoRecording() {
        videoCapture!!.stopRecording()
        startedRecording = false
        //Toaster.toast("Recording stopped")
        binding!!.btnStop.setText("Record Button")
    }

    private fun openUploadVideoActivity(videoPath: Uri) {
        //val intent = Intent(this, UploadVideoActivity::class.java)
        //intent.putExtra(OpenCameraActivity.VIDEO_URL, videoPath.toString())
        //startActivity(intent)
        setFragmentResult("requestKey", bundleOf("videoURL" to videoPath.toString()))
        findNavController().popBackStack()
    }

    private val executor: Executor
        get() = ContextCompat.getMainExecutor(requireActivity())
    `;
};

export const generateVideoViewImports = (fragment) => {
  if (findComponentsByKeyValue(fragment, "name", "VideoView").length == 0)
    return "";

  return `
    import android.annotation.SuppressLint
    import android.net.Uri
    import android.os.Build
    import android.os.CountDownTimer
    import android.os.Environment
    import android.widget.Button
    import androidx.annotation.RequiresApi
    import androidx.camera.core.CameraSelector
    import androidx.camera.core.Preview
    import androidx.camera.core.VideoCapture
    import androidx.camera.lifecycle.ProcessCameraProvider
    import androidx.core.content.ContextCompat
    import androidx.core.os.bundleOf
    import androidx.fragment.app.setFragmentResult
    import androidx.lifecycle.LifecycleOwner
    import androidx.navigation.fragment.findNavController
    import com.google.common.util.concurrent.ListenableFuture
    import com.manaknight.app.extensions.viewBinding
    import org.koin.android.ext.android.inject
    import java.io.File
    import java.text.DecimalFormat
    import java.text.NumberFormat
    import java.util.Date
    import java.util.concurrent.Executor
    `;
};

export const getVideoRecorderFragmentFields = (fragment) => {
  if (findComponentsByKeyValue(fragment, "name", "VideoView").length == 0)
    return "";

  return `
  var btnStop: Button? = null
  private var cameraProviderListenableFuture: ListenableFuture<ProcessCameraProvider>? = null
  private var videoCapture: VideoCapture? = null
  private var startedRecording = false
  private var countDownTimer: CountDownTimer? = null
    `;
};

export const generateVideoViewInteractions = (fragment) => {
  if (findComponentsByKeyValue(fragment, "name", "VideoView").length == 0)
    return "";

  return `
  binding.home.setOnClickListener {
    findNavController().popBackStack()
    }

    init()

    `;
};
