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

public class MapParameterControllerRange : MapParameterController
{
    public float minValue = 0f;
    public float maxvalue = 1f;
    public int stepsAmount = 5;

    Slider valueSlider;

    float currentGoalValue;
    float currentValue;

    protected override void Awake()
    {
        base.Awake();

        valueSlider = GetComponentInChildren<Slider>();
        valueSlider.minValue = 0f;
        valueSlider.maxValue = stepsAmount - 1;
        valueSlider.wholeNumbers = true;
        valueSlider.onValueChanged.AddListener(OnValueChanged);
        valueSlider.interactable = false;
    }

    public override void ActivateManualControl(bool manual)
    {
        base.ActivateManualControl(manual);
        valueSlider.interactable = manual;
    }

    void OnValueChanged(float newValue)
    {
        newValue = newValue / ((float) (stepsAmount - 1));
        newValue *= (maxvalue - minValue);
        newValue += minValue;
        currentValue = newValue;
        AssignValue(MapParametersManager.Instance.playerQuad, currentValue);
        CheckNewValue();
    }

    public override void Init()
    {
        valueSlider.value = valueSlider.minValue;
        currentGoalValue = currentValue;
    }

    protected override void SelectRandomValue(MeshRenderer resultQuad)
    {
        while(IsCorrect())
        {
            float randomValue = ((float) UnityEngine.Random.Range(0, stepsAmount)) / ((float) (stepsAmount - 1));
            randomValue *= (maxvalue - minValue);
            randomValue += minValue;
            currentGoalValue = randomValue;
        }
        //Debug.Log("Did select random value for " + gameObject.name + ": " + currentGoalValue);
        AssignValue(resultQuad, currentGoalValue);
    }

    protected override void AutoUpdate()
    {
        //float randomValue = ((float) UnityEngine.Random.Range(0, stepsAmount)) / ((float) (stepsAmount - 1));
        //randomValue *= (maxvalue - minValue);
        //randomValue += minValue;
        //valueSlider.value = randomValue;
        valueSlider.value = UnityEngine.Random.Range(0, stepsAmount);
        //Debug.Log("Autoupdate " + gameObject.name + " with goal " + currentGoalValue + " and new current value " + currentValue);
    }

    void AssignValue(MeshRenderer quad, float value)
    {
        quad.material.SetFloat(shaderParameterName, value);
    }

    public override bool IsCorrect()
    {
        return currentValue == currentGoalValue;
    }
}
