using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class BarCloseAlert : Indicator
    {
        private HullMovingAverage _hma;

        [Parameter("Bar Close Sound File", Group = "Sounds", DefaultValue = "C:\\Windows\\Media\\Alarm07.wav")]
        public string BarCloseSoundFileName { get; set; }

        [Parameter("HMA Sound File", Group = "Sounds", DefaultValue = "C:\\Windows\\Media\\Alarm08.wav")]
        public string HmaSoundFileName { get; set; }

        [Parameter("HMA Period", Group = "HMA Settings", DefaultValue = 200)]
        public int HmaPeriod { get; set; }

        protected override void Initialize()
        {
            _hma = Indicators.HullMovingAverage(Bars.ClosePrices, HmaPeriod);
            Bars.BarClosed += OnBarsClosed;
        }

        private void OnBarsClosed(BarClosedEventArgs obj)
        {
            // 1. Play Bar Close Sound
            if (!string.IsNullOrEmpty(BarCloseSoundFileName))
            {
                Notifications.PlaySound(BarCloseSoundFileName);
            }

            // 2. Check HMA High/Low
            // We need enough bars for Last(0), Last(1), Last(2)
            if (Bars.Count < 3 || string.IsNullOrEmpty(HmaSoundFileName))
            {
                return;
            }

            // Adjusted Indexing per user requirement:
            // Last(0) is treated as the bar that just closed.
            double hmaJustClosed = _hma.Result.Last(0);
            double hmaPrev = _hma.Result.Last(1);
            double hmaPrePrev = _hma.Result.Last(2);

            // Check for High Point (Peak): Rising then Falling
            // Shape: / \
            bool isHigh = (hmaPrePrev < hmaPrev) && (hmaPrev > hmaJustClosed);

            // Check for Low Point (Valley): Falling then Rising
            // Shape: \ /
            bool isLow = (hmaPrePrev > hmaPrev) && (hmaPrev < hmaJustClosed);

            if (isHigh || isLow)
            {
                Notifications.PlaySound(HmaSoundFileName);
            }
        }

        public override void Calculate(int index)
        {
        }

        protected override void OnDestroy()
        {
            Bars.BarClosed -= OnBarsClosed;
        }
    }
}