using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

// @NOTE:
// Some interesting animated capture
// https://gist.github.com/bitbutter/302da1c840b7c93bc789

//[ExecuteInEditMode]
public class ScreenShot : MonoBehaviour
{
    public string m_filePath = "";
    public string m_fileName = "shot";
    public bool m_appendDate = true;
    public bool m_appendResolution = true;
    public bool m_customCapture = false;
    public bool m_requestCapture = false; // set this from the editor inspector to request a capture when in edit mode (if paused, unpause to go)
    public float m_captureDelay = 0;
    public bool m_autoPause = false;
    public bool m_autoPauseCapture = false;
    public int m_autoPauseFrame = 0;

    void Update()
    {
        if (m_autoPause && Time.frameCount >= m_autoPauseFrame)
        {
            m_autoPause = false;
            if (m_autoPauseCapture)
            {
                StartCoroutine(CaptureShot());
            }
            Time.timeScale = 0;
            Debug.Break();
        }

        if (Input.GetKeyDown(KeyCode.F12) || m_requestCapture)
        {
            m_requestCapture = false;
            StartCoroutine(CaptureShot());
        }
    }

    IEnumerator CaptureShot()
    {
        // Yield to next frame and then start the rendering
        yield return new WaitForEndOfFrame();

        int width = Screen.width;
        int height = Screen.height;

        Directory.CreateDirectory(m_filePath);

        string fileName = m_filePath;

        if (fileName.Length > 0 && fileName[fileName.Length - 1] != '/')
            fileName += "/";

        fileName += m_fileName;

        if (m_appendResolution)
            fileName += "_" + width.ToString() + "x" + height.ToString();

        if(m_appendDate)
            fileName += "_" + System.DateTime.Now.ToString("yyMMdd_hhmmss");

        fileName += ".png";

        if(m_customCapture)
            CaptureCustomScreenShot(fileName, width, height); 
        else
            ScreenCapture.CaptureScreenshot(fileName);

        Debug.Log("ScreenShot: " + fileName);

        if(m_captureDelay > 0)
            yield return new WaitForSeconds(m_captureDelay);
    }

    void CaptureCustomScreenShot(string fileName, int resWidth, int resHeight)
    {
        Camera camera = Camera.main;

        RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
        camera.targetTexture = rt;
        Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false);
        camera.Render();
        RenderTexture.active = rt;
        screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
        camera.targetTexture = null;
        RenderTexture.active = null;
        Destroy(rt);
        
        byte[] bytes = screenShot.EncodeToPNG();

        System.IO.File.WriteAllBytes(fileName, bytes);
    }
}
