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

public class DialogManager : MonoBehaviour
{
    public GUISkin skin;    
    
    [SerializeField]
    float textSpeed = 30;
    int lineIndex = 0;
    float letterIndex = 0;
    string currentText = "";
    public Dialog.DiagScene scene;
    public bool play = false;
    public Texture photo;

    public void PrepareScene(Dialog.DiagScene s)
    {
        lineIndex = 0;
        letterIndex = 0;
        currentText = "";
        scene = s;
        play = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (!play) return;

        letterIndex += Time.deltaTime * textSpeed;
        letterIndex = Mathf.Min(letterIndex, scene.text[lineIndex].Length);

        if (Input.GetMouseButtonDown(0))
        {
            if (letterIndex >= scene.text[lineIndex].Length)
            {
                letterIndex = 0;
                lineIndex++;
                // end of scene
                if (lineIndex >= scene.text.Length - 1)
                {
                    photo = null;
                    play = false;
                    //scene.trigger?.Invoke(0);
                }
            }
            else letterIndex = scene.text[lineIndex].Length;
        } 

        currentText = scene.text[lineIndex].Substring(0, (int)letterIndex);
    }

    private void OnGUI()
    {
        //GUI.skin.box.alignment = TextAnchor.UpperLeft;
        if (!play) return;

        GUI.skin = skin;

        if (photo != null) {
            float rate = photo.width > photo.height ? photo.width / (Screen.width * .8f) : photo.height / (Screen.height * .8f);
            var x = Screen.width / 2 - photo.width/rate / 2;
            var y = Screen.height / 2 - photo.height / rate / 2;
            GUI.DrawTexture(new Rect(x, y, photo.width / rate, photo.height / rate), photo);
        }

        Rect positionName = new Rect(30, Screen.height * 3 / 4 - 24, 256, 24);
        Rect position = new Rect(Screen.width * 1 / 12, Screen.height * 3 / 4, Screen.width * 5 / 6, Screen.height / 4);

        GUI.Box(position, currentText);
        if(scene.name[lineIndex]!="")
        GUI.Box(positionName, scene.name[lineIndex]);
        
    }
}
