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

public class UIGameOver : MonoBehaviour {

    private const string DISPLAY_GAME_OVER = "DISPLAY_GAME_OVER";
    private const string DISPLAY_LOCAL_SCORE = "DISPLAY_LOCAL_SCORE";
    private const string DISPLAY_SERVER_SCORE = "DISPLAY_SERVER_SCORE";
    private const string DEFAULT_USERNAME = "Player 1";

    [SerializeField]
    private string serverUrl = "";

    [SerializeField, Range(1, 50)]
    private int maxUsers = 10;

    [SerializeField]
    private GUISkin customSkin;
    

    private string currentDisplay;

    private bool submitted;
    private bool restarting;

    private float displayWidth;
    private float displayHeight;
    private float btnHeight = 30;
    private float btnWidth = 240;
    private float btnX;
    private float posY;
    private float leftMargin;
    private float verticalSpacing;

    private UserData user;
    private LocalHighScore localHighScore;
    private Vector2 scrollPosition;

    private void Awake()
    {
        Messenger.AddListener(GameEvent.GAME_OVER, OnGameOver);

        // Get the Local High Score Script component attached to the game object
        localHighScore = GetComponent<LocalHighScore>();

        // If no Local High Score script attached, add one
        if (localHighScore == null)
        {
            localHighScore = gameObject.AddComponent<LocalHighScore>();
        }
    }

    private void OnDestroy()
    {
        Messenger.RemoveListener(GameEvent.GAME_OVER, OnGameOver);
    }

    // Use this for initialization
    void Start () {
        user = new UserData();
        user.Name = DEFAULT_USERNAME;
        user.Score = 0;
    }
	
	// Update is called once per frame
	void Update () {
		
	}

    private void OnGameOver()
    {
        StartCoroutine(DoGameOver());
    }

    private IEnumerator DoGameOver()
    {
        yield return new WaitForSeconds(2f);
        currentDisplay = DISPLAY_GAME_OVER;
        submitted = false;
        restarting = false;
    }

    private void OnGUI()
    {
        if (!Managers.IsGameOver || string.IsNullOrEmpty(currentDisplay))
            return;

        GUI.skin = customSkin;


        displayWidth = Screen.width * 0.8f;
        displayHeight = Screen.height * 0.8f;
        btnX = (displayWidth - btnWidth) * 0.5f;
        posY = 50;
        leftMargin = (displayWidth - 400) * 0.5f;
        verticalSpacing = Mathf.Max(displayHeight * 0.015f, 5f);
        //Debug.Log(displayHeight * 0.015f);
        //Debug.Log(Screen.height * 0.015f);
        //Debug.Log("verticalSpacing: " + verticalSpacing);
        // Debug.Log("Current Display: " + currentDisplay);

        using (new GUI.GroupScope(new Rect(Screen.width * 0.1f, Screen.height * 0.1f, displayWidth, displayHeight)))
        {
            if (!restarting)
            {
                switch (currentDisplay)
                {
                    case DISPLAY_GAME_OVER:
                        DisplayGameOver();
                        break;
                    case DISPLAY_LOCAL_SCORE:
                        DisplayLocalScore();
                        break;
                    case DISPLAY_SERVER_SCORE:
                        break;
                    default:
                        break;
                }

                if (GUI.Button(CreateButtonRect(posY), "RESTART"))
                {
                    restarting = true;
                    Messenger.Broadcast(GameEvent.GAME_RESTART);
                }
            } else
            {
                CreateBackgroundBox("RESTARTING");
                GUI.Label(new Rect(leftMargin, posY, 400, 25), "Loading ...", GUI.skin.GetStyle("CustomText"));
            }
        }        
        
    }

    private void CreateBackgroundBox(string header)
    {
        GUI.Box(new Rect(0, 0, displayWidth, displayHeight), 
            header, GUI.skin.GetStyle("Box2"));
    }

    private Rect CreateButtonRect(float btnY)
    {
        return new Rect(btnX, btnY, btnWidth, btnHeight);
    }

    private void DisplayGameOver()
    {
        posY = 50;
        CreateBackgroundBox("GAME OVER");
        
        GUI.Label(new Rect(leftMargin, posY, 400, 25), "Final Score: " + Managers.Player.Score.ToString("#,##0"), GUI.skin.GetStyle("CustomText3"));
        posY += 25 + verticalSpacing;
        if (!submitted)
        {
            GUI.Label(new Rect(leftMargin, posY, 400, 25), "Enter Your Name:", GUI.skin.GetStyle("CustomText3"));
            posY += 25 + verticalSpacing;
            user.Name = GUI.TextField(new Rect(btnX, posY, btnWidth, 40), user.Name, 8);
            posY += 40 + verticalSpacing;

            // Create SUBMIT button and when clicked do submit routine
            if (GUI.Button(CreateButtonRect(posY), "SUBMIT"))
            {
                submitted = true;
                // Update the score and save the user data
                user.Score = Managers.Player.Score;
                localHighScore.SaveUserData(user);
            }
            posY += btnHeight + verticalSpacing;
        }

        if (GUI.Button(CreateButtonRect(posY), "LOCAL HIGH SCORE"))
        {
            // Load the local high score data and change the GUI display option
            localHighScore.LoadUserData();
            currentDisplay = DISPLAY_LOCAL_SCORE;
        }
        posY += btnHeight + verticalSpacing;

        if (GUI.Button(CreateButtonRect(posY), "SERVER HIGH SCORE"))
        {
            currentDisplay = DISPLAY_SERVER_SCORE;
        }
        posY += btnHeight + verticalSpacing;
    }


    private void DisplayLocalScore()
    {
        posY = 50;
        CreateBackgroundBox("LOCAL HIGH SCORE");
        posY += 25 + verticalSpacing;

        int NumberUsers = localHighScore.NumberUsers;
        if (NumberUsers > 0)
        {
            // Set height and width of scrollable area
            float localDisplayHeight = Mathf.Min(displayHeight - 100, 150);
            float localDisplayWidth = 400 - leftMargin * 2;

            // Create a scollable region
            using (var scrollViewScope = new GUI.ScrollViewScope(
                new Rect(leftMargin, posY, 400, localDisplayHeight),
                scrollPosition,
                new Rect(0, 0, localDisplayWidth, NumberUsers * 60)))
            {
                scrollPosition = scrollViewScope.scrollPosition;
                for (int i = 0; i < NumberUsers; i++)
                {
                    UserData user = localHighScore.GetUserDataAt(i);
                    using (new GUILayout.HorizontalScope())
                    {
                        GUILayout.Label((i + 1).ToString() + ". " + user.Name + " ", GUI.skin.GetStyle("Name"));
                        GUILayout.Label(user.Score.ToString("#,##0"), GUI.skin.GetStyle("Score"));
                    }
                }
            };

            posY += localDisplayHeight + verticalSpacing;
        }

        // posY += verticalSpacing;
        // Add a back button so user can return to Game over menu
        if (GUI.Button(CreateButtonRect(posY), "BACK"))
        {
            currentDisplay = DISPLAY_GAME_OVER;
        }
        posY += btnHeight + verticalSpacing;
    }


}
