
using Game.Network.DTO;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug;


public class LevelManager : MonoBehaviour
{
    #region 플레이어 관련
    [SerializeField] private GameObject[] _playableCharacterPrefabs; //플레이어가 될수 있는 캐릭터들 프리팹 할당
    public GameObject[] PlayableCharacterPrefabs { get { return _playableCharacterPrefabs; } private set { _playableCharacterPrefabs = value; } } 
    public GameObject CurrentCharacter { get; private set; } // 현재 캐릭터
    public PlayerCharacterController CurrentCharacterController { get { return CurrentCharacter == null ? null : CurrentCharacter.GetComponent<PlayerCharacterController>(); } } // 현재 캐릭터의 컨트롤러
    public int CurrentCharacterIdx { get; private set; } //현재캐릭터 인덱스
    #endregion

    private void Awake()
    {
      
    }

    public void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (scene.name == "GameStartScene")
        {
            InputManager.Instance.SetUIInputMap("IntroUI");
        }

        if (scene.name == "GameScene")
        {

            List<UserCharacter> myCharacters = DataManager.Instance.MyCharacters;

            if (myCharacters != null && myCharacters.Count > 0 && PlayableCharacterPrefabs != null && PlayableCharacterPrefabs.Length > 0)
            {

                Dictionary<string, PlayerCharacterController> playableCharacterPrefabsDic = PlayableCharacterPrefabs
                .Select(p => p.GetComponent<PlayerCharacterController>())
                .Where(pcc => pcc != null && pcc.PlayerCharacterIdentity != null)
                .ToDictionary(pcc => pcc.PlayerCharacterIdentity.CharacterCode, pcc => pcc);

                foreach (UserCharacter uc in myCharacters)
                {
                    //내가 가진 캐릭터 코드와 일치하는 플레이어블 캐릭터 프리팹 객체들 
                    if (playableCharacterPrefabsDic.TryGetValue(uc.CharacterCode, out PlayerCharacterController pcc))
                    {
                        ApplyCharacterInfo(pcc, uc);
                    }
                }

                bool defaultCharacterFlag = false;

                for (int i = 0; i < PlayableCharacterPrefabs.Length; i++)
                {

                    GameObject pc = PlayableCharacterPrefabs[i];
                    if (pc.TryGetComponent<PlayerCharacterController>(out PlayerCharacterController pcc) && pcc.PlayerCharacterIdentity.IsDefaultControl)
                    {
                        CurrentCharacter = PlayableCharacterPrefabs[i];
                        CurrentCharacterIdx = i;
                        CurrentCharacterController.PlayerCharacterIdentity.SynchronizeControll();
                        defaultCharacterFlag = true;
                        break;
                    }
                }
                if(!defaultCharacterFlag)
                {
                    //0번 캐릭터를 현재캐릭터로 설정
                    if (PlayableCharacterPrefabs != null && PlayableCharacterPrefabs.Length > 0)
                    {
                        CurrentCharacter = PlayableCharacterPrefabs[0];
                        CurrentCharacterIdx = 0;
                        CurrentCharacterController.PlayerCharacterIdentity.SynchronizeControll();
                    }
                }
            }
            else
            {
                //0번 캐릭터를 현재캐릭터로 설정
                if (PlayableCharacterPrefabs != null && PlayableCharacterPrefabs.Length > 0)
                {
                    CurrentCharacter = PlayableCharacterPrefabs[0];
                    CurrentCharacterIdx = 0;
                    CurrentCharacterController.PlayerCharacterIdentity.SynchronizeControll();
                }
            }

            InputManager.Instance.SetUIInputMap("InGameUI");
            InputManager.Instance.SetCharacterInputMap("Character");

            //일단 하나의 액션맵만 사용
            InputManager.Instance.ActiveOnlyOneActionMap("Character"); 

            //카메라 줌 매핑
            InputManager.Instance.OnMouseScrollEvent += GameManager.Instance.Camera.ZoomCamera;

            //이동 매핑
            InputManager.Instance.OnMoveEvent += CurrentCharacterController.MoveInput;
            InputManager.Instance.OnSprintEvent += CurrentCharacterController.SprintInput;
            InputManager.Instance.OnJumpEvent += CurrentCharacterController.JumpInput;
            InputManager.Instance.OnAimToggleEvent += CurrentCharacterController.AimToggleInput;
            InputManager.Instance.OnLookEvent += CurrentCharacterController.LookInput;
            InputManager.Instance.OnDodgeEvent += CurrentCharacterController.DodgeInput;

            //공격매핑
            //InputManager.Instance.OnNormalAttackEvent;
            //InputManager.Instance.OnHeavyAttackEvent;

            //기타매핑
            InputManager.Instance.OnInteractionEvent += CurrentCharacterController.InteractInput;

            //UI매핑
            InputManager.Instance.OnKeyDown_IKeyEvent += GameManager.Instance.InGameUI.InventoryToggle;

            //화면 켜기
        }

    }

    private void ApplyCharacterInfo(PlayerCharacterController pcc, UserCharacter uc)
    {
        pcc.PlayerCharacterStat.MaxHp = uc.MaxHp;
        pcc.PlayerCharacterStat.MaxMp = uc.MaxMp;
        pcc.PlayerCharacterStat.Lv = uc.Lv;
        pcc.PlayerCharacterStat.StrStat = uc.StrStat;
        pcc.PlayerCharacterStat.IntStat = uc.IntStat;
        pcc.PlayerCharacterIdentity.IsDefaultControl = uc.DefaultControl;
    }

    private void OnDestroy()
    {
        if(InputManager.Instance != null)
        {

            //카메라 줌 매핑 해제
            if (GameManager.Instance != null && GameManager.Instance.Camera != null)
            {
                InputManager.Instance.OnMouseScrollEvent -= GameManager.Instance.Camera.ZoomCamera;
            }


            if(CurrentCharacterController != null)
            {
                //이동 매핑 해제
                InputManager.Instance.OnMoveEvent -= CurrentCharacterController.MoveInput;
                InputManager.Instance.OnSprintEvent -= CurrentCharacterController.SprintInput;
                InputManager.Instance.OnJumpEvent -= CurrentCharacterController.JumpInput;
                InputManager.Instance.OnAimToggleEvent -= CurrentCharacterController.AimToggleInput;
                InputManager.Instance.OnLookEvent -= CurrentCharacterController.LookInput;
                InputManager.Instance.OnDodgeEvent -= CurrentCharacterController.DodgeInput;
                //InputManager.Instance.OnNormalAttackEvent;
                //InputManager.Instance.OnHeavyAttackEvent;
            }

            if(GameManager.Instance != null)
            {
                InputManager.Instance.OnKeyDown_IKeyEvent -= GameManager.Instance.InGameUI.InventoryToggle;
            }
        }
    }
}
