using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class PlayerRandomizer : MonoBehaviour {
	
	GameGenerator playerGenerator;
	[HideInInspector]
	public Transform playerHead;
    PhotonView view;

    // Use this for initialization
    void Awake () {
		playerGenerator = FindObjectOfType<GameGenerator> ();
		if (!playerGenerator || !playerHead)
			return;
        view = GetComponent<PhotonView>();
		if (view && !view.IsMine && PhotonNetwork.IsConnected)
            return;
        Random.InitState(System.DateTime.Now.Millisecond + (int)(Time.unscaledTime * 1000));
		RandomizePlayer ();
        GameGenerator.SetRandomToOldSeed();
    }

    void RandomizePlayer () {
		int t = Random.Range (0, playerGenerator.generator.playerTextures.Count);
        AddSkinTexture(t);

		int h = Random.Range (0, playerGenerator.generator.hairStyles.Count);
		int hc = Random.Range (0, playerGenerator.generator.hairColors.Count);
        AddHair(h, hc);

		if (view && PhotonNetwork.IsConnected) {
            PhotonDebugger.IncrementNumberOfMessages("set player textures");
            view.RPC("SetPlayerPlayerTextures", RpcTarget.OthersBuffered, view.ViewID, t, h, hc);
        }
	}

    void AddSkinTexture(int skinTextureIndex) {
        Material m = new Material(Shader.Find("Standard"));
        m.mainTexture = playerGenerator.generator.playerTextures[skinTextureIndex];
        GetComponentInChildren<SkinnedMeshRenderer>().material = m;
    }

    void AddHair(int hairStyleIndex, int hairColorIndex) {
        GameObject myHair = Instantiate(playerGenerator.generator.hairStyles[hairStyleIndex], playerHead.position, Quaternion.Euler(playerGenerator.generator.hairStyles[hairStyleIndex].transform.eulerAngles), playerHead);
        if (myHair.transform.childCount > 0)
            myHair.transform.GetChild(0).GetComponent<SkinnedMeshRenderer>().material = playerGenerator.generator.hairColors[hairColorIndex];
        else
            myHair.GetComponent<MeshRenderer>().material = playerGenerator.generator.hairColors[hairColorIndex];
    }

    [PunRPC]
    void SetPlayerPlayerTextures(int viewID, int skinTextureIndex, int hairStyleIndex, int hairColorIndex) {
        if (!view)
            view = GetComponent<PhotonView>();

        if (view.ViewID != viewID)
            return;

        AddSkinTexture(skinTextureIndex);
        AddHair(hairStyleIndex, hairColorIndex);
    }
}
