using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Assets.Scripts.Battle;
using Assets.Scripts.Player;
using UnityEngine;

namespace Assets.Scripts.UI.Placeholder
{
    class BattleUI : IBattleUI {
        [SerializeField] private GameObject[] _spritesPrefab;
        [SerializeField] private GameObject _arrowPrefab;
        [SerializeField] private GameObject _barPrefab;
        [SerializeField] private GameObject _cooldownBarPrefab;
        [SerializeField] private GameObject _noRangePrefab;
        [SerializeField] private Sprite[] _battleBgs;
        [SerializeField] private Sprite[] _battleFgs;
        [SerializeField] private GameObject _battleBGObject;
        [SerializeField] private GameObject _battleFGObject;

        private readonly List<GameObject> _sprites = new List<GameObject>();
        private GameObject _arrow;

        protected void Start() {
            GameCore.Instance.BattleUI = this;
        }

        public override void StartBattle(BattleEngine battle, int act) {
            _battleBGObject.GetComponent<SpriteRenderer>().sprite = _battleBgs[act];
            _battleFGObject.GetComponent<SpriteRenderer>().sprite = _battleFgs[act];
            foreach (var m in battle.AllMobs) {
                //TODO: Load enemy sprites correctly
                var go = (GameObject)Instantiate(_spritesPrefab[m.SpriteIndex], new Vector3(1000, 0, 0), Quaternion.identity);
                var battleSprite = go.GetComponent<BattleSprite>();
                battleSprite.SetMob(m, battle, this, go.GetComponent<SkeletonAnimation>());
                _sprites.Add(go);

                battleSprite.SetCooldownBar(MakeBar(true));
                battleSprite.SetHealthBar(MakeBar(false));
            }
        }

        private Bar MakeBar(bool gauge) {
            var go = (GameObject) Instantiate(gauge?_cooldownBarPrefab:_barPrefab);
            go.transform.SetParent(transform, true);
            return go.GetComponent<Bar>();
        }

        public override void Clear() {
            foreach (var s in _sprites) {
                DestroyObject(s);
            }
            _sprites.Clear();
        }

        public override void SetMoveCursor(Mob mob, int getBattlePosition, int moveTo) {
            bool shouldHaveArrow = getBattlePosition != moveTo;
            if (shouldHaveArrow && _arrow == null) {
                _arrow = (GameObject) Instantiate(_arrowPrefab);
            }
            if (!shouldHaveArrow && _arrow != null) {
                DestroyObject(_arrow);
            }
            if (shouldHaveArrow) {
                _arrow.transform.position = new Vector3(BattleSprite.BattleToWorldX(moveTo + (moveTo > getBattlePosition ? 0.5f : -0.5f),mob.GetAllegiance()), 2f, 0);
            }
        }
    }
}
