﻿using UnityEngine;
using UnityEngine.UI;

namespace VRPlayerSDK.sample
{
    public class SamplePlayerTouchUI : MonoBehaviour
    {
        public Button PlayBn;
        public Button StopBn;
        public Toggle Show3Dto2DBn;
        public Text InfoText;
        public Text ProgressText;
        public Dropdown SampleListDropDown;
        public Slider PlayProgress;
        public Text versionText;
        public HuaweiVRPlayer VRPlayer;
        public InputField PlayUrl;

        public Camera DiractionCamera;

        // 当前正在播放的视频Url
        private string curPlayUrl = "";
        private PLAY_STATE curPlayState = PLAY_STATE.IDLE;   // 0, stop/not start;  1, playing,  2, pause

        private const string LAST_URL_SAVE_KEY = "last_play_url";
        private enum PLAY_STATE
        {
            IDLE, PLAYING, PAUSE
        };

        // Use this for initialization
        void Start()
        {
            versionText.text = "Player Core Ver: " + VRPlayer.GetPlayerCoreVersion() + " ,Player API Ver: " + VRPlayer.GetPlayerAPIVersion();
            InitSampleList();
        }

        // Update is called once per frame
        void Update()
        {
            if (VRPlayer.IsPlaying())
            {
                long movieLength = VRPlayer.GetDuration();
                long movieCurrent = VRPlayer.GetCurrentPosition();
                SetPlayingProgress(movieLength, movieCurrent);
            }
        }

        private void InitSampleList()
        {
            var defaultUrl = "http://8kvr.hwcloudlive.com/vrfov/chunwan8k012_8K/index.mpd";
            var url = PlayerPrefs.GetString(LAST_URL_SAVE_KEY, defaultUrl);
            if (url.Length <= 5)
            {
                // invalid value use default url.
                url = defaultUrl;
            }

            // here need set url value to input field
            PlayUrl.text = url;
            SetPlayingInfo("播放地址已经加载");
        }

        public void SetPlayingInfo(string info)
        {
            InfoText.text = info;
        }

        public void SetPlayingProgress(long total, long current)
        {
            ProgressText.text = FormatTime(current) + "/" + FormatTime(total);
            if (total > 0)
            {
                float progress = (float)current / (float)total;
                Debug.Log("current progress:" + progress);
                PlayProgress.value = progress;
            }
            else
            {
                PlayProgress.value = 0f;
            }
        }

        public void OnSeek()
        {
            float toValue = PlayProgress.value;
            Debug.Log("OnSeek:" + toValue);

            long movieLength = VRPlayer.GetDuration();
            float pos = movieLength * toValue;
            VRPlayer.SeekTo((long)pos);
        }

        private PlayerMediaData getMediaData(string url)
        {
            if (url.StartsWith("http"))
            {
                // http or https, is 8K FOV Dash Live Video
                return new PlayerMediaData
                {
                    type = PlayerType.PlayerType8K,
                    is8kfov = true,
                    isLive = true,
                    playURL = url
                };
            }

            // Not http, is rtmp 360 4k 2D Live video
            return new PlayerMediaData
            {
                type = PlayerType.PlayerType2D_360,
                is8kfov = false,
                isLive = true,
                playURL = url
            };
        }

        private void play(string url)
        {
            // first or after stop
            Debug.Log("播放新媒体");
            SetPlayingInfo("正在起播:" + url);
            var media = getMediaData(url);
            VRPlayer.SetMediaData(media);
            curPlayUrl = url;
            curPlayState = PLAY_STATE.PLAYING;

            PlayerPrefs.SetString(LAST_URL_SAVE_KEY, url);  // save to last prefs

            if (!media.isLive)
            {
                // live video can't pause
                PlayBn.GetComponentInChildren<Text>().text = "Pause";
            }
        }

        private void pause()
        {
            // 暂停播放
            Debug.Log("暂停");
            VRPlayer.Pause();
            curPlayState = PLAY_STATE.PAUSE;
            PlayBn.GetComponentInChildren<Text>().text = "Play";
            SetPlayingInfo("暂停播放");
        }

        private void resume()
        {
            // 恢复播放
            VRPlayer.Resume();
            curPlayState = PLAY_STATE.PLAYING;
            PlayBn.GetComponentInChildren<Text>().text = "Pause";
        }

        private void stop()
        {
            VRPlayer.Release();
            curPlayState = PLAY_STATE.IDLE;
            PlayBn.GetComponentInChildren<Text>().text = "Play";
            SetPlayingProgress(0, 0);
            SetPlayingInfo("停止播放");
        }


        public void OnPlayBnClicked()
        {
            Debug.Log("点击播放/暂停按钮");
            string url = PlayUrl.text.Trim();
            if (url.Length < 5)
            {
                // not a valid url
                ShowToast("Error: Not a valid url!");
                return;
            }

            if (!url.Equals(curPlayUrl))
            {
                // start a new url play, stop old first
                OnStopBnClicked();
            }

            switch (curPlayState)
            {
                case PLAY_STATE.IDLE:
                    // first or after stop
                    play(url);
                    break;
                case PLAY_STATE.PLAYING:
                    // 暂停播放
                    pause();
                    break;
                case PLAY_STATE.PAUSE:
                    // 恢复播放
                    resume();
                    break;
                default:
                    break;
            }
            //ShowToast("Old:" + title + ", new:" + PlayBn.GetComponentInChildren<Text>().text);
        }

        public void OnShow2DToggle()
        {
            Debug.Log("show2D Toggle按钮," + Show3Dto2DBn.isOn);
            VRPlayer.Show3Dto2D(Show3Dto2DBn.isOn);
        }

        public void OnStopBnClicked()
        {
            Debug.Log("停止播放按钮");
            if (curPlayState == PLAY_STATE.IDLE)
            {
                // not start or has stopped.
                return;
            }

            stop();
        }

        /**
         * 将毫秒数格式化为HH:MM:SS.sss
         */
        private string FormatTime(long miniSec)
        {
            string outstr = "";
            if (miniSec >= 3600000)
            {
                long hh = miniSec / 3600000;
                outstr = hh.ToString() + ":";
                miniSec -= hh * 3600000;
            }
            long mm = miniSec / 60000;
            outstr += mm.ToString() + ":";
            miniSec -= mm * 60000;

            long ss = miniSec / 1000;
            outstr += ss.ToString() + ".";
            miniSec -= ss * 1000;

            outstr += miniSec.ToString();

            return outstr;
        }

        private void ShowToast(string text)
        {
            AndroidJavaClass player = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject act = player.GetStatic<AndroidJavaObject>("currentActivity");
            AndroidJavaClass toast = new AndroidJavaClass("android.widget.Toast");
            act.Call("runOnUiThread", new AndroidJavaRunnable(() =>
            {
                toast.CallStatic<AndroidJavaObject>("makeText", act, text, toast.GetStatic<int>("LENGTH_LONG")).Call("show");
            }));
        }
    }
}

