using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NightScout.Interfaces;

namespace NightScout
{
    public class RaspberryPiAudioAlert : IAlerter
    {
        public String PlayerCommandLine { get; set; }
        public String KillCommand { get; set; }
        public String AlertFileName { get; set; }

        protected IRaspberryPiButtonSource ButtonSource;

        private Boolean playing = false;


        public RaspberryPiAudioAlert()
        {
            this.PlayerCommandLine = "\"mpg123 -q {0}\"";
            this.KillCommand = "pkill mpg123";
            this.AlertFileName = "~/ratm.mp3";
        }

        public RaspberryPiAudioAlert(String playerCommandline)
            : base()
        {
            this.PlayerCommandLine = playerCommandline;
        }

        public RaspberryPiAudioAlert(String playerCommandline, IRaspberryPiButtonSource buttonSource)
            : this(playerCommandline)
        {
            this.ButtonSource = buttonSource;
            this.ButtonSource.ButtonStateChange += ButtonSource_ButtonStateChange;
        }

        public RaspberryPiAudioAlert(IRaspberryPiButtonSource buttonSource)
            : this()
        {
            this.ButtonSource = buttonSource;
            this.ButtonSource.ButtonStateChange += ButtonSource_ButtonStateChange;
        }

        private void ButtonSource_ButtonStateChange(bool obj)
        {
            Console.WriteLine("Button state change: {0}", obj);
            if(obj)
                StopAlerts();
        }

        public void StartAlert()
        {
            if (!playing)
            {
                playing = true;
                Process.Start("/bin/bash", String.Format("-c {0}", String.Format(PlayerCommandLine,AlertFileName )));
            }
        }

        public void StartUrgentAlert()
        {
            StartAlert();
        }

        public void StartStaleDataAlert()
        {
            StartAlert();
        }

        public void StopAlerts()
        {
            Process.Start("/bin/bash", "-c \"pkill mpg123\"");
            playing = false;
        }
    }
}
