//>>> _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.IDdf361466_1094_409a_a4b4_63c55c2fea2a
{
    public class Class_StoreImage : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            Image = 0,
            ImagePath = 1,
            StoreTrigger = 2
        }
        //<<< _inputids

        //>>> _outputids
        private enum OutputId
        {
            Image = 0
        }
        //<<< _outputids

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) 
        {
            //>>> __params
            var ImageInput = inputs[(int)InputId.Image];
            var ImagePath = inputs[(int)InputId.ImagePath].Eval(context).Text;
            var StoreTrigger = inputs[(int)InputId.StoreTrigger].Eval(context).Value;
            //<<< __params

            var imageResult = ImageInput.Eval(context);
            var image = imageResult.Image;
            var depth = imageResult.DepthImage;

            bool triggerUpFlankDetected = _lastStoreTrigger < 0.5 && StoreTrigger > 0.5;
            _lastStoreTrigger = StoreTrigger;

            if (triggerUpFlankDetected)
            {
                FileInfo fi = new FileInfo(ImagePath);
                Directory.CreateDirectory(fi.DirectoryName);

                if (image != null)
                {
                    var filename = fi.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(fi.Name) + ".png";
                    Texture2D.ToFile(D3DDevice.Device.ImmediateContext, image, ImageFileFormat.Png, fi.FullName);
                    Logger.Info(this,"image stored {0}", filename);
                }
                if (depth != null)
                {
                    var filename = fi.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(fi.Name) + "_depth.dds";
                    Texture2D.ToFile(D3DDevice.Device.ImmediateContext, depth, ImageFileFormat.Dds, filename);
                    Logger.Info(this,"depth image stored {0}", filename);
                }
            }

            context.Image = image;
            context.DepthImage = depth;
            return context;
        }
        
        float _lastStoreTrigger;
    }
}

