using UniRx;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using SFB;
using System.Collections;
using System.Runtime.InteropServices;
public class ScreenshotButton : MonoBehaviour, IPointerDownHandler
{
#if UNITY_WEBGL && !UNITY_EDITOR
    //
    // WebGL
    //
    [DllImport("__Internal")]
    private static extern void DownloadFile(string gameObjectName, string methodName, string filename, byte[] byteArray, int byteArraySize);

    // Broser plugin should be called in OnPointerDown.
    public void OnPointerDown(PointerEventData eventData) {
        StartCoroutine(ScrrenCapture(new Rect(0, 0, Screen.width, Screen.height)));
    }
    IEnumerator ScrrenCapture(Rect rect)
    {
        Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        yield return new WaitForEndOfFrame();
        tex.ReadPixels(rect, 0, 0);
        tex.Apply();
        var _textureBytes = tex.EncodeToPNG();
        DownloadFile(gameObject.name, "OnFileDownload", "Screenshot.png", _textureBytes, _textureBytes.Length);
    }
    // Called from browser
    public void OnFileDownload() {
        //Framework.Instance.LoadInformationCue("截图保存成功,路径为:" + path, Color.white);
    }
#else
    public void OnPointerDown(PointerEventData eventData) { }
    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Button>().OnClickAsObservable()
            .Subscribe(_ => UIManager.Instance.Show<ScreenshotPanel>());
    }


#endif
}