#if UNITY_EDITOR
using System;
using UniRx;
using UniRx.Triggers;
using UnityEngine;

namespace MyGame.Scenes.MiniGame.Scripts
{
    public class DebugGame : MonoBehaviour
    {
        [SerializeField] private BoolReactiveProperty isDebug = new BoolReactiveProperty();
        private LineRenderer lineRendererCenter;
        private LineRenderer lineRendererFront;
        [SerializeField] private Transform character;

        private void Start()
        {
            isDebug.AddTo(this);
            var debugObject = new GameObject(){name = "debugObject"};

            var orgScale = debugObject.transform.localScale;
            isDebug.Subscribe(x =>
            {
                debugObject.name = x.ToString();
                debugObject.transform.localScale = x ? orgScale : Vector3.zero;
            }).AddTo(this);
            
            var lineRendererObject = new GameObject();
            lineRendererObject.transform.parent = debugObject.transform;
            lineRendererObject.transform.localScale = Vector3.one;
            lineRendererCenter = lineRendererObject.AddComponent<LineRenderer>();
            lineRendererCenter.useWorldSpace = false;
            lineRendererCenter.sharedMaterial = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Material>("Sprites-Default.mat");
            lineRendererCenter.startWidth = .1f;
            lineRendererCenter.sortingOrder = 20;
            lineRendererFront = Instantiate(lineRendererCenter, debugObject.transform);
            lineRendererCenter.startColor = Color.blue;
            lineRendererCenter.endColor = Color.blue;
            lineRendererFront.startColor = Color.green;
            lineRendererFront.endColor = Color.green;

            var boundsSize = character.GetComponent<Collider2D>()?.bounds.size ?? default;
            var centerOffset = new Vector3(-boundsSize.x / 2, boundsSize.y / 2);
            var frontOffset = new Vector3(boundsSize.x / 2, -boundsSize.y / 2);
            
            lineRendererCenter.SetPosition(0, character.position + centerOffset);
            lineRendererFront.SetPosition(0, character.position + frontOffset);
            Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(.1f))
                .DelayFrameSubscription(2)
                .Subscribe(_ =>
                {
                    lineRendererCenter.positionCount++;
                    lineRendererCenter.SetPosition(lineRendererCenter.positionCount-1, character.position + centerOffset);
                    lineRendererFront.positionCount++;
                    lineRendererFront.SetPosition(lineRendererFront.positionCount-1, character.position + frontOffset);
                }).AddTo(this);

            this.UpdateAsObservable()
                .Where(_ => Input.GetKeyDown(KeyCode.R))
                .Subscribe(_ =>
                {
                    UnityEngine.SceneManagement.SceneManager.LoadScene(gameObject.scene.buildIndex);
                }).AddTo(this);
        }
    }
}
#endif