using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;

namespace Framefield.Core.IDc4bd45e3_8b11_480c_acf7_30306a50555f
{
    public class Class_RandomStepper : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            JumpTrigger = 0,
            ResetTrigger = 1,
            DefaultValue = 2,
            ValueRange = 3,
            JumpFactor = 4
        }
        //<<< _inputids
        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) 
        {
            //>>> _params
            var JumpTrigger = inputs[(int)InputId.JumpTrigger].Eval(context).Value;
            var ResetTrigger = inputs[(int)InputId.ResetTrigger].Eval(context).Value;
            var DefaultValue = inputs[(int)InputId.DefaultValue].Eval(context).Value;
            var ValueRange = inputs[(int)InputId.ValueRange].Eval(context).Value;
            var JumpFactor = inputs[(int)InputId.JumpFactor].Eval(context).Value;
            //<<< _params
            
            bool isJumping= JumpTrigger - _lastJumpTrigger > 0.5f;
            _lastJumpTrigger = JumpTrigger;
            
            bool isResetting = ResetTrigger - _lastResetTrigger > 0.5f;
            _lastResetTrigger = ResetTrigger;
            
            if(isResetting) {
                _value = DefaultValue;
                context.Value = _value;
                return context;
            }
            
            if(isJumping) 
            {
                var jump= _rand.NextDouble() * _direction * JumpFactor * ValueRange;
                var r2 = _rand.NextDouble();
                
                //Logger.Info(""+_rand.NextDouble());
                
                var distanceFromDefault = Math.Abs(_value - DefaultValue) / ValueRange;
                var moveBackToCenter = r2 < distanceFromDefault;
                                
                if(  moveBackToCenter ) {
                    Logger.Info(this, "Move back");
                    _direction = _value < DefaultValue ? 1 : -1;
                }
                _value += (float)jump;
            }
            
            context.Value = _value;
            return context;
        }
        
        float _lastJumpTrigger;
        float _lastResetTrigger;
        float _value;
        float _direction = 1;
        Random _rand = new Random(1212);
    }
}

