/* -LICENSE-START-
** Copyright (c) 2017 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
** 
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
** 
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/

using System;
using DeckLinkAPI;
using System.Collections.Generic;

namespace SignalGenCSharp
{
    public delegate void DeckLinkVideoOutputHandler(bool prerolling);
    public delegate void DeckLinkPlaybackStoppedHandler();
    public delegate void DeckLinkAudioOutputHandler();
    public class DeckLinkOutputDevice : IDeckLinkVideoOutputCallback, IDeckLinkAudioOutputCallback, IEnumerable<IDeckLinkDisplayMode>
    {
        private IDeckLink       m_deckLink;
        private IDeckLinkOutput m_deckLinkOutput;
        
        public DeckLinkOutputDevice(IDeckLink deckLink)
        {
            m_deckLink = deckLink;

            // Get output interface
            try
            {
                m_deckLinkOutput = (IDeckLinkOutput)m_deckLink;
            }
            catch (InvalidCastException)
            {
                // No output interface found, eg in case of DeckLink Mini Recorder
                return;
            }

            // Provide the delegate to the audio and video output interfaces
            m_deckLinkOutput.SetScheduledFrameCompletionCallback(this);
            m_deckLinkOutput.SetAudioCallback(this);
        }

        public event DeckLinkVideoOutputHandler VideoFrameCompleted;
        public event DeckLinkPlaybackStoppedHandler PlaybackStopped;
        public event DeckLinkAudioOutputHandler AudioOutputRequested;
        
        public IDeckLink deckLink
        {
            get { return m_deckLink; }
        }

        public IDeckLinkOutput deckLinkOutput
        {
            get { return m_deckLinkOutput; }
        }

        public string deviceName
        {
            get
            {
                string deviceName;
                m_deckLink.GetDisplayName(out deviceName);
                return deviceName;
            }
        }

        public void RemoveAllListeners()
        {
            AudioOutputRequested    = null;
            PlaybackStopped         = null;
            VideoFrameCompleted     = null;
        }

        IEnumerator<IDeckLinkDisplayMode> IEnumerable<IDeckLinkDisplayMode>.GetEnumerator()
        {
            IDeckLinkDisplayModeIterator displayModeIterator;
            m_deckLinkOutput.GetDisplayModeIterator(out displayModeIterator);
            return new DisplayModeEnum(displayModeIterator);
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new InvalidOperationException();
        }

        #region callbacks
        // Explicit implementation of IDeckLinkVideoOutputCallback and IDeckLinkAudioOutputCallback
        void IDeckLinkVideoOutputCallback.ScheduledFrameCompleted(IDeckLinkVideoFrame completedFrame, _BMDOutputFrameCompletionResult result)
        {
            // When a video frame has been completed, generate event to schedule next frame
            VideoFrameCompleted(false);
        }

        void IDeckLinkVideoOutputCallback.ScheduledPlaybackHasStopped()
        {
            PlaybackStopped();
        }

        void IDeckLinkAudioOutputCallback.RenderAudioSamples(int preroll)
        {
            // Provide further audio samples to the DeckLink API until our preferred buffer waterlevel is reached
            AudioOutputRequested();

            if (preroll != 0)
            {
                m_deckLinkOutput.StartScheduledPlayback(0, 100, 1.0);
            }
        }
        #endregion
    }

    class DisplayModeEnum : IEnumerator<IDeckLinkDisplayMode>
    {
        private IDeckLinkDisplayModeIterator m_displayModeIterator;
        private IDeckLinkDisplayMode m_displayMode;

        public DisplayModeEnum(IDeckLinkDisplayModeIterator displayModeIterator)
        {
            m_displayModeIterator = displayModeIterator;
        }

        IDeckLinkDisplayMode IEnumerator<IDeckLinkDisplayMode>.Current
        {
            get { return m_displayMode; }
        }

        bool System.Collections.IEnumerator.MoveNext()
        {
            m_displayModeIterator.Next(out m_displayMode);
            return m_displayMode != null;
        }

        void IDisposable.Dispose()
        {
        }

        object System.Collections.IEnumerator.Current
        {
            get { return m_displayMode; }
        }

        void System.Collections.IEnumerator.Reset()
        {
            throw new InvalidOperationException();
        }
    }
}
