using System;
using System.ComponentModel;
using System.Windows;
using PeerSDK.Wrapper;

namespace PeerSDK.Samples
{
    public partial class LiveStreamWindow : Window, INotifyPropertyChanged
    {
        public LiveStreamWindow(Peer peer)
        {
            Stream = peer.CreateLiveStream();
            Stream.ErrorOccurred += Stream_ErrorOccurred;
            Stream.VideoArrived += Stream_VideoArrived;
            Stream.AudioArrived += Stream_AudioArrived;

            Available = new string[Stream.Available];
            for (int i = 0; i < Available.Length; i++)
                Available[i] = "Stream " + i;

            DataContext = this;

            InitializeComponent();
        }

        public PeerStream Stream { get; private set; }

        public string[] Available { get; private set; }

        void Start_OnClick(object sender, RoutedEventArgs e)
        {
            Stream.Start();
        }

        void Window_Closed(object sender, EventArgs e)
        {
            if (Stream != null)
                Stream.Dispose();
        }

        void Stream_ErrorOccurred(object sender, ErrorOccurredEventArgs e)
        {
            MessageBox.Show(this, e.ToString());
        }

        void Stream_VideoArrived(object sender, VideoArrivedEventArgs e)
        {
            Type = IrfFrameType.Video;
            Video = e;

            DownloadRate = Stream.DownloadRate;

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Type"));
                PropertyChanged(this, new PropertyChangedEventArgs("Video"));
                PropertyChanged(this, new PropertyChangedEventArgs("Audio"));
                PropertyChanged(this, new PropertyChangedEventArgs("DownloadRate"));
            }
        }

        void Stream_AudioArrived(object sender, AudioArrivedEventArgs e)
        {
            Type = IrfFrameType.Audio;
            Audio = e;

            DownloadRate = Stream.DownloadRate;

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Type"));
                PropertyChanged(this, new PropertyChangedEventArgs("Video"));
                PropertyChanged(this, new PropertyChangedEventArgs("Audio"));
                PropertyChanged(this, new PropertyChangedEventArgs("DownloadRate"));
            }
        }

        public IrfFrameType Type { get; private set; }
        public VideoArrivedEventArgs Video { get; private set; }
        public AudioArrivedEventArgs Audio { get; private set; }

        public long DownloadRate { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}