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

public class MusicManager : MonoBehaviour
{

    public AudioClip[] levelMusicChangeArray;
    private static AudioSource audi;
    private AudioClip thisLevelMusic;
    private int level;
    public GameObject player;
    public GameObject gunPrefab;
                    
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
        audi = gameObject.GetComponent<AudioSource>();

        if (SceneManager.GetActiveScene().buildIndex == 0)
        {
            int level = SceneManager.GetActiveScene().buildIndex;
            thisLevelMusic = levelMusicChangeArray[level];
            if (thisLevelMusic) /*if there is some music attached*/
            {
                audi.clip = thisLevelMusic;
                audi.loop = true;
                audi.Play();
            }
        }
    }

    private void Update()
    {
        if (SceneManager.GetActiveScene().buildIndex == 2)
        { audi.volume = 0.6f; }
        if (SceneManager.GetActiveScene().buildIndex == 0)
        { Cooownter.Coownter = 0; }
        if (Cooownter.Coownter >= 3) { SceneManager.LoadScene(4); }
    }

    private void OnLevelWasLoaded(int level)
    {
        if (SceneManager.GetActiveScene().buildIndex > 1 && SceneManager.GetActiveScene().buildIndex < 5)
        {
            GameObject currentPlayer = Instantiate(player, new Vector3(-27.21f, 6f, player.transform.position.z), Quaternion.identity);
            currentPlayer.GetComponent<CreateObject>().canShoot = true;
            GameObject currentGun = Instantiate(gunPrefab, currentPlayer.transform.position, Quaternion.identity);
            currentGun.transform.localPosition = new Vector3(currentPlayer.transform.position.x +0.2f, currentPlayer.transform.position.y, currentPlayer.transform.position.z);
            currentGun.transform.localScale = new Vector3(-1f, 1, 1);
            currentGun.transform.parent = currentPlayer.transform;
        }
    }

    // Use this for initialization
    public static void ChangeVolume(float volume)
    {
        audi.volume = volume;
    }

    // Update is called once per frame
    private void OnLevelWasLoaded()
    {
        if (thisLevelMusic)
        {
            audi.Stop();
        }
        int level = SceneManager.GetActiveScene().buildIndex;
        thisLevelMusic = levelMusicChangeArray[level];
        if (thisLevelMusic) /*if there is some music attached*/
        {
            audi.clip = thisLevelMusic;
            audi.loop = true;
            audi.Play();
        }
    }
}