using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;

namespace Rokid.MRC
{
    public class CameraController : UnitySingleton<CameraController>
    {
        //相机控制
        public Transform FollowParent;
        public Camera clientCamera;

        //渲染纹理
        public RenderTextureDescriptor RTDesc;
        public RenderTexture renderTexture;

        private int textureID;
        private bool isConnected;

        public PlayerData curPlayer;

        private CameraParam curCamParam;

        public override void Awake()
        {
            base.Awake();

            clientCamera = GetComponent<Camera>();

            CreateRTDescriptor();

            //先创建
            TransmissionClient.Create();
        }

        public void SetCameraParam(CameraParam newParam)
        {
            Debug.LogWarning($"SetCameraParam X : {newParam.pixelXY.x} , Y : {newParam.pixelXY.y} , Width : {newParam.pixel.x} , Height : {newParam.pixel.y} , FOV : {newParam.fov} , FocalLength : {newParam.focalLength} , Near Far : {newParam.nearClipPlane}-{newParam.farClipPlane} ");

            //Rect camRect = new Rect(newParam.pixelXY.x, newParam.pixelXY.y, newParam.pixel.x, newParam.pixel.y);
            //clientCamera.pixelRect = camRect;

            //相机长宽高由此决定
            clientCamera.targetTexture = CreateCompositeRenderTexture(newParam);
            
            clientCamera.fieldOfView = newParam.fov;
            clientCamera.focalLength = newParam.focalLength;
            clientCamera.nearClipPlane = newParam.nearClipPlane;
            //clientCamera.farClipPlane = newParam.farClipPlane;

            clientCamera.farClipPlane = 100;
        }

        public void ChangeFollowTargetOrientation(bool isPortrait)
        {
            if(isPortrait)
            {
                //竖屏
                FollowParent.localRotation = Quaternion.identity;
            }
            else
            {
                //横屏
                FollowParent.localRotation = Quaternion.Euler(0, 0, 90);
            }
        }

        private void Update()
        {
            //相机跟随
            if(MRCDriver.Instance.UseGlobalRenderCamera && FollowParent != null)
            {
                transform.position = FollowParent.position;
                transform.rotation = FollowParent.rotation;
            }

            //纹理传输
            if(!isConnected)
            {
                return;
            }

            TransmissionClient.UpdateTextureData();

            //PushTextureWithStream();
        }

        private void CreateRTDescriptor()
        {
            RTDesc = new RenderTextureDescriptor();
            //RTDesc.graphicsFormat = GraphicsFormat.R16G16B16A16_SFloat;
            RTDesc.graphicsFormat = GraphicsFormat.R8G8B8A8_SRGB;

            //RenderTextureFormat参数比较关键，会影响最终输出
            RTDesc.colorFormat = RenderTextureFormat.ARGB32;
            //RTDesc.colorFormat = RenderTextureFormat.ARGBFloat;
            RTDesc.dimension = TextureDimension.Tex2D;
            RTDesc.volumeDepth = 1;
            RTDesc.msaaSamples = 2;
        }

        public RenderTexture CreateCompositeRenderTexture(CameraParam camParam)
        {
            curCamParam = camParam;

            RTDesc.width = (int)camParam.pixel.x;
            RTDesc.height = (int)camParam.pixel.y;

            Debug.Log($"CreateCompositeRenderTexture Width : {RTDesc.width} Height : {RTDesc.height} FrameRate : {camParam.frameRate}  BitRate : {camParam.bitRate}");

            //创建新的RT
            renderTexture = new RenderTexture(RTDesc);
            renderTexture.Create();
            renderTexture.name = "CompositeColorTex" + Time.time;

            //RenderTexture.active = renderTexture;

            //页面设置和刷新
            MessageCenter.SendMessage(GlobalDefine.CameraParamFinished, renderTexture);

            StartConnectStream();

            return renderTexture;
        }

        public RenderTexture CreateRenderTexture(CameraParam newParam, string texName = "Tex")
        {
            RTDesc.height = (int)newParam.pixel.y;
            RTDesc.width = (int)newParam.pixel.x;

            //创建新的RT
            RenderTexture rt = new RenderTexture(RTDesc);
            rt.name = texName;

            //页面设置和刷新
            MessageCenter.SendMessage(GlobalDefine.CameraParamFinished, rt);

            return rt;
        }

        //开启视频流
        public void StartConnectStream()
        {
            //todo，目前不需要IP
            curPlayer = PlayerManager.Instance.GetVideoPlayer();
            if(curPlayer != null)
            {
                if(string.IsNullOrEmpty(curPlayer.ClientIP))
                {
                    Debug.LogError($"StartConnectStream : {curPlayer.PlayerName} IP is Empty");

#if UNITY_EDITOR
                    //测试
                    ServerMessageDispatcher.Instance.SyncStartStream(curPlayer.ClientId);
#endif

                }
                else
                {
                    textureID = (int)renderTexture.GetNativeTexturePtr();

                    //Debug.Log($"TransmissionClient.Start IP : {curPlayer.ClientIP} TexID : {textureID} Width : {renderTexture.width} Height : {renderTexture.height} FrameRate : {camParam.frameRate} colorBufferID : {renderTexture.colorBuffer.GetNativeRenderBufferPtr()}");

                    TransmissionClient.Start(textureID, renderTexture.width, renderTexture.height, curCamParam.frameRate, curCamParam.bitRate);

                    //通知该客户端可以开始拉流
                    ServerMessageDispatcher.Instance.SyncStartStream(curPlayer.ClientId);
                }
            }
            else
            {
                Debug.LogError("There is no video client");
            }

            isConnected = true;
        }

        public void ShutDownComposition()
        {
            isConnected = false;

            if(renderTexture != null)
            {
                renderTexture.Release();
            }
            renderTexture = null;
        }

        //ReadPixel的方式读取纹理，目前已经不用
        private Texture2D shotImage;
        private byte[] bytes;
        private Rect rect;
        private void PushTextureWithStream()
        {
            if(renderTexture != null)
            {
                // 将当前活动的 RenderTexture 设置为我们要读取的纹理
                RenderTexture.active = renderTexture;
                if(shotImage == null)
                {
                    shotImage = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
                    shotImage.filterMode = FilterMode.Point;
                }
                rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
                shotImage.ReadPixels(rect, 0, 0);
                // 获取纹理的原始数据
                bytes = shotImage.GetRawTextureData();

                //TransmissionClient.PushTextureByteData(bytes, bytes.Length);
                RenderTexture.active = null;
                bytes = null;
            }
        }
    }
}