﻿#if UNITY_5_3_OR_NEWER
#define NOESIS
using Noesis;
using UnityEngine;
#else
using System.Windows;
using System.Windows.Threading;
#endif
using System.ComponentModel;
using System.Windows.Input;
using System;

namespace BindingMemoryLeak
{
    public class SessionImage : Image
    {
        public SessionImage()
        {
            this.Loaded += (s, e) => { ((SessionImage)s)?.LoadAsset(); };
            this.Unloaded += (s, e) => { ((SessionImage)s)?.UnloadAsset(); };
        }

        public int SessionId
        {
            get { return (int)GetValue(SessionIdProperty); }
            set { SetValue(SessionIdProperty, value); }
        }

        public static readonly DependencyProperty SessionIdProperty = DependencyProperty.Register(
            "SessionId", typeof(int), typeof(SessionImage), new PropertyMetadata(0, OnLoadAsset));

        public bool UseMipMaps
        {
            get { return (bool)GetValue(UseMipMapsProperty); }
            set { SetValue(UseMipMapsProperty, value); }
        }

        public static readonly DependencyProperty UseMipMapsProperty = DependencyProperty.Register(
            "UseMipMaps", typeof(bool), typeof(SessionImage), new PropertyMetadata(true, OnLoadAsset));


        private static void OnLoadAsset(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is SessionImage sessionImage)
            {
                sessionImage.LoadAsset();
            }
        }

#if NOESIS
        public void LoadAsset()
        {
            UnloadAsset();

            var sessionName = SessionId < 0 ? "SESSION_REST" : $"SESSION_{SessionId}";

            Source = LoadImage.GetImageSource("Trainings", $"{sessionName}.png", UseMipMaps, out _currentTexture);
        }

        public void UnloadAsset()
        {
            if (_currentTexture != null)
            {
                UnityEngine.Object.Destroy(_currentTexture);
                _currentTexture = null;
            }
        }

        private Texture2D _currentTexture;
#else
        public void LoadAsset() { }
        public void UnloadAsset() { }
#endif

    }
}