using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System.Drawing;
using System.Runtime.InteropServices;

public class Recorder : MonoBehaviour
{
    public Camera cameraToRecord;
    public int frameRate = 30;
    public string outputFilePath = "Assets/output.avi";

    public bool playing = true;

    private VideoWriter videoWriter;
    private int frameWidth;
    private int frameHeight;

    private void Start()
    {
        // Initialize video writer
        frameWidth = Screen.width;
        frameHeight = Screen.height;

        videoWriter = new VideoWriter(outputFilePath, VideoWriter.Fourcc('M', 'J', 'P', 'G'), frameRate, new System.Drawing.Size(frameWidth, frameHeight), true);

        if (!videoWriter.IsOpened)
        {
            Debug.LogError("Failed to open video writer.");
            return;
        }

        // Start capturing frames
        StartCoroutine(CaptureFrames());
    }

    private IEnumerator CaptureFrames()
    {
        while (playing)
        {
            yield return new WaitForEndOfFrame();
            CaptureFrame();
        }
    }

    private void CaptureFrame()
    {
        RenderTexture renderTexture = new RenderTexture(frameWidth, frameHeight, 24);
        cameraToRecord.targetTexture = renderTexture;
        Texture2D screenShot = new Texture2D(frameWidth, frameHeight, TextureFormat.RGB24, false);

        cameraToRecord.Render();
        RenderTexture.active = renderTexture;
        screenShot.ReadPixels(new Rect(0, 0, frameWidth, frameHeight), 0, 0);
        screenShot.Apply();

        cameraToRecord.targetTexture = null;
        RenderTexture.active = null;
        Destroy(renderTexture);

        // Convert Texture2D to byte array
        byte[] pixels = screenShot.GetRawTextureData();

        // Create Mat from byte array
        Mat frame = new Mat(frameHeight, frameWidth, DepthType.Cv8U, 3);
        Marshal.Copy(pixels, 0, frame.DataPointer, pixels.Length);

        // Flip the image vertically
        CvInvoke.Flip(frame, frame, FlipType.Vertical);
        // Convert BGR to RGB
        CvInvoke.CvtColor(frame, frame, ColorConversion.Bgr2Rgb);

        // Write frame to video
        videoWriter.Write(frame);
    }

    private void OnApplicationQuit()
    {
        StopAllCoroutines();
        videoWriter.Dispose();
    }
}