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


public class GameManager : MonoBehaviour
{
    public int ThrowsInTrial;
    public enum Condition { Motor, Gaze, Motor2Gaze, Gaze2Motor, BullsEye2Motor, Motor2BullsEye }; //Options to select Condition that shall be Played in Unity
    public Condition condition;
    public enum Hand { LeftHand, RightHand };           //select Hand that user is using
    public Hand hand;
    public bool SpawnDebugPoints;                   //Debug Points shall be displayed or not?
    public int SubjectID;                             //Field to enter SUbj ID
    public String ExpName;
    private int Points;                 
    public int ThrowCounter;
    private bool first;
    public int ActiveTargetNr;
    public bool ActGame;
   

    private string SysTimestampGamestart;
    private string GameTimestampstart;
    private string GameTimestampEnd;
    private string SysTimestampGameEnd;

    public Material BWMaterial;
    public Material ColMaterial;

    public GameObject Ball;
    public GameObject Punkte;
    public GameObject Wuerfe;
    public GameObject TargetPodest;
    public GameObject StudyEndText;

    public int oldTarg;


    public static GameManager instance;

    public scri clock;


    private System.Random rndm;

    // used to start the timer only when player throws first ball
    public static bool startTimer;

    private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            instance = this;
        }

        ThrowCounter = 0;
        ActGame = false;
        first = true;

        StudyEndText.SetActive(false);

        rndm = new System.Random();

        RecordingController.Instance.SubjectID = SubjectID;
        RecordingController.Instance.ExperimentName = ExpName;

    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("s"))      //Press Key S to start game / spawn Ball
        {
            StartGame();
            

        }

        if (Input.GetKeyDown("e"))          //Press E to force Game to quit
        {
            EndGame();
            
        }
        if (Input.GetKeyDown("r"))              //Press R to reset the Ball
        {
            Ballmanager.instance.ForceBallReset(Ball);
            
        }

        if (ThrowCounter > (ThrowsInTrial-1) && ActGame == true) //Automatically end Game after desired number of throws have been reached
        {
            EndGame();           
        }

 
    }



    private void StartGame()  //Set values and initiates everything needed to start the game
    {
        ActGame = true;
        StudyEndText.SetActive(false);
        Debug.Log("Started the Game @" + DateTime.Now);
        Ball.SetActive(true);
        SysTimestampGamestart = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
        GameTimestampstart = Time.time.ToString();
        clock.gameStarted = true;
        NewRound();

    }

    private void EndGame() //Set values and everything to force end the Game also save the Data
    {
        ActGame = false;
        StudyEndText.SetActive(true);
        Debug.Log("Ended the Game @" + DateTime.Now);
        SysTimestampGameEnd = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
        GameTimestampEnd = Time.time.ToString();
        clock.gameFinished = true;
        Ball.SetActive(false);
        MaterialManager.instance.DeactivateTarg();
        EyeTrackingCSV_Recorder.instance.EyeTrackingDataBuffer.Add(EyeTrackingCSV_Recorder.instance.CaptureStudyInfo(SysTimestampGameEnd, GameTimestampEnd, "GameEnd", 99));
        //ThrowCounter = 0;
    }

    private void NewRound()     //Method that handles everything needed to 
    {
        oldTarg = ActiveTargetNr;
        ActionHandler.instance.lockedGazePoint = Vector3.zero;
        ActionHandler.instance.targetActButtonPress = false;
        if (first)
        {
            Ballmanager.instance.ready4nextRound = true;
            EyeTrackingCSV_Recorder.instance.EyeTrackingDataBuffer.Add(EyeTrackingCSV_Recorder.instance.CaptureStudyInfo(SysTimestampGamestart, GameTimestampstart, "GameStart", ActiveTargetNr));
            first = false;
        }
        else
        {
            if (ActGame)
            {
                EyeTrackingCSV_Recorder.instance.EyeTrackingDataBuffer.Add(EyeTrackingCSV_Recorder.instance.CaptureStudyInfo(SysTimestampGamestart, GameTimestampstart, "NewRound", ActiveTargetNr));

                StartCoroutine(Ballmanager.instance.ResetBall(Ballmanager.instance.BallCollider));
                
            }
        }
    }

    public void BallhitTarget()
    {
        UpdateGameValues();
        
        if (ThrowCounter < ThrowsInTrial)
        {
            
            NewRound();
        }
        else
        {
            StudyEndText.SetActive(true);
        }
    }

    public void SetThrowCounter(int incrby)
    {
        ThrowCounter = ThrowCounter + incrby;
        Counter.wuerfe = ThrowCounter;
    }

    private void SetPointCounter(int pt)
    {
        points.Points = Points;
    }

    private int GetThrowCounter()
    {
        return ThrowCounter;
    }

    private void UpdateGameValues()
    {
        
        int PointsThisRound = ScoreCalc.instance.DistanceToPoints(ScoreCalc.instance.CalcDistancetoBullsEye(Ball.transform.position, ActiveTargetNr));
        Points = ScoreCalc.instance.sumScore(PointsThisRound);
        MainStudy_Recorder.instance.ScoreperRound = PointsThisRound;
        SetPointCounter(Points);
    }
}