//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using

using System.IO;

namespace Framefield.Core.ID8b8991c8_1193_4c95_9e43_d9e9a8982985
{
    public class Class_CountInFile : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            CountTrigger = 0,
            ResetTrigger = 1,
            FilePath = 2
        }
        //<<< _inputids
        
        int ReadNumberFromFile(string filepath) 
        {
            if( !File.Exists( filepath)) {
                Logger.Error(this,"File not found: '{0}'", filepath);
                return 0;
            }
            else {                
                return  (int)Double.Parse( File.ReadAllText(filepath) );
            }
        }
        
        void WriteNumberToFile(string filepath, int number) 
        {
            File.WriteAllText(filepath, String.Format("{0}", number));
        }
        
        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) {
            //>>> _params
            var CountTrigger = inputs[(int)InputId.CountTrigger].Eval(context).Value;
            var ResetTrigger = inputs[(int)InputId.ResetTrigger].Eval(context).Value;
            var FilePath = inputs[(int)InputId.FilePath].Eval(context).Text;
            //<<< _params
            
                        
            bool flankDetected = CountTrigger >= 0.5 && _oldTrigger <= 0.5;
            _oldTrigger = CountTrigger;
            
            if( FilePath != _lastFilePath || flankDetected ) {
                _lastFilePath = FilePath;
                _count = ReadNumberFromFile(FilePath);
                _count++;
                WriteNumberToFile(FilePath, _count);
            }
            
            if( ResetTrigger == 1.0) {
                _count = 0;
                WriteNumberToFile(FilePath, _count);
            }
            _lastValue= CountTrigger;
            context.Value= _count;
            return context;
        }
        
        int _count = 0;
        float _lastValue= float.NaN;
        float _oldTrigger;
        string _lastFilePath;
        
    }
}

