//>>> _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.ID10141962_a1dc_4e08_9e1d_8b7ba9663c48
{
    public class Class_LoadSmesh : OperatorPart.Function,
                                   Framefield.Core.OperatorPartTraits.IMeshSupplier
    {
        // IMeshSupplier
        public void AddMeshesTo(ICollection<Mesh> meshes)
        {
            UpdateMesh(new OperatorPartContext(), OperatorPart.Connections);

            if (_meshResource != null)
            {
                _meshResource.Meshes.ForEach(meshes.Add);
            }
        }

        public override void Dispose()
        {
            Utilities.DisposeObj(ref _meshResource);
        }

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx)
        {

            try
            {
                UpdateMesh(context, inputs);

                context.Renderer.SetupEffect(context);
                foreach (var mesh in _meshResource.Meshes)
                {
                    context.Renderer.Render(mesh, context);
                }
            }
            catch (Exception)
            {
                //Logger.Error(this,"error");
            }

            return context;
        }

        private void UpdateMesh(OperatorPartContext context, IList<OperatorPart> inputs)
        {
            if (!Changed) 
                return;

            var FilePath = inputs[0].Eval(context).Text;

            Dispose();
            if(File.Exists( FilePath)) {
                _meshResource = ResourceManager.ReadSmesh(FilePath);
            }
            else {
                Logger.Warn(this, "File does not exist '{0}'", FilePath);
            }
                
                
            Changed = false;
        }

        private MeshResource _meshResource;
    }
}


