using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Team
{
    public Dictionary<string, Member> Members;
    public Player myPlayer;

    protected int myPlayerID = -1;
    protected string letterz = "abcdefghijklmnopqrstuvwxyz";
    protected string numberz = "0123456789";

    public Team(Player player, int memberCount)
    {
        Members = new Dictionary<string, Member>();

        myPlayer = player;
        myPlayerID = Game.CurrentGame.Players.IndexOf(myPlayer); // lol sorry

        for(int i=0; i<memberCount; i++)
        {
            Member newMember = CreateMember();
            Members.Add(newMember.Name, newMember);
        }
    }

    protected Member CreateMember()
    {
        GameObject prefab = Game.CurrentGame.MemberPrefab;
        Transform SpawnParent = Game.CurrentGame.TeamMemberParent.transform;
        Vector3 SpawnPos = SpawnParent.transform.position;
        Quaternion SpawnRot = Quaternion.identity;

        GameObject mObj;
        Member m;

        Vector3 randOffset = GenetateSpawnPos();

        mObj = GameObject.Instantiate(prefab, SpawnPos + randOffset, SpawnRot, SpawnParent);
        m = mObj.GetComponent<Member>();
        m.Init(GenMemberName(), this, myPlayer);
        m.InitialSpawnPos = randOffset;

        return m;
    }

    public Vector3 GenetateSpawnPos()
    {
        Vector3 randOffset = Vector3.zero;
        bool positionSafe = false;

        Random.InitState(12);
		Random.InitState (NetworkCommandRunner.RandomGameSeed);

        while(!positionSafe)
        {
            float randomX = Mathf.RoundToInt(Random.Range(-3, 3)) + 0.5f;
            float randomZ = Mathf.RoundToInt(Random.Range(1, 5)) + 0.5f;
            int playerSideDir = (myPlayerID == 0 ? -1 : 1);
            randOffset = new Vector3(playerSideDir * randomX, 0.2f, playerSideDir * randomZ);

            positionSafe = true;
            if(Member.AllMembers !=null)
            {
                foreach(var m in Member.AllMembers)
                {
                    if(m.Value.InitialSpawnPos == randOffset)
                    {
                        positionSafe = false;
                    }
                }
            }
        }

        return randOffset;
    }

    public void MoveMember(Member member, Vector2 direction)
    {
        member.Move(direction);
    }

    // design rule: the worse a method is the more protected it should be
    private string GenMemberName()
    {
        string newName = null;

        switch(myPlayerID)
        {
            case 0:
                newName = ""+letterz[Members.Count];
                break;
            case 1:
                newName = ""+numberz[Members.Count];
                break;
        }

        return newName;
    }
}
