﻿using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.IO;
using UnityEngine.SceneManagement;
using System.Collections.Generic;

public class LevelLoad : MonoBehaviour {
	public GameObject DUI;
	public GameObject smoking;
	public GameObject landscape;

	public float timer = 15f;
	public string nextLevel;

	private float audioTimer = 1.5f; //delay to sound clip start
	private float locationTimer = 0.5f;
	private GameObject player;
	private bool levelEnding = false;
	private string locationData = "";
    private string FPSData = "";
    private float FPSTimer = 30f;
    private int FPSCounter = 0;

    public AudioClip clip1;
    public AudioClip clip2;

    public AudioClip AudioURLfloor1;
    public AudioClip AudioURLfloor2;
    public AudioClip AudioURLfloor3;
    public AudioClip AudioURLfloor4_1;
    public AudioClip AudioURLfloor4_2;
    public AudioClip AudioURLfloor4_3;
    public AudioClip AudioURLEnd;
    private Texture2D loadScreen;
    private GUIStyle loadScreenStyle;
    private PlayerGUI playerGUI;
    void OnGUI() {
        if (levelEnding) {
            if (loadScreen == null)
            {
                loadScreen = new Texture2D(1, 1);
                loadScreen.SetPixel(0, 0, Color.black);
                loadScreen.Apply();
            }
            if (loadScreenStyle == null) {
                loadScreenStyle = new GUIStyle();
            }
            loadScreenStyle.normal.background = loadScreen;
            loadScreenStyle.normal.textColor = Color.white;
            loadScreenStyle.fontSize = 30;
            loadScreenStyle.alignment = TextAnchor.MiddleCenter;

            GUI.Box(new Rect(0, 0, Screen.width, Screen.height), "Loading...", loadScreenStyle);
        }
    }
    void Start () {
        Time.timeScale = 1;
        playerGUI = FindObjectOfType<PlayerGUI>();
        PlayerPrefs.SetInt ("Shots", 0);
		PlayerPrefs.SetInt ("Hits", 0);
		PlayerPrefs.SetInt ("Damage", 0);
		PlayerPrefs.SetInt ("Deaths", 0);
		PlayerPrefs.SetInt ("Kills", 0);

		player = GameObject.FindGameObjectWithTag ("Player");
		if(DUI != null && landscape != null){
	        if (PlayerPrefs.GetInt("Posters") == 0)
	        {
	            DUI.active = false;
		    	smoking.active = false;
	            landscape.active = true;
	        }
	        if (PlayerPrefs.GetInt("Posters") == 1)
	        {
	            DUI.active = true;
		    	smoking.active = false;
	            landscape.active = false;
	        }
			if (PlayerPrefs.GetInt("Posters") == 2)
			{
				DUI.active = false;
				smoking.active = true;
				landscape.active = false;
			}
		}
        if (Application.loadedLevelName == "floor1") {
            clip1 = AudioURLfloor1;
        }
        if (Application.loadedLevelName == "floor2")
        {
            clip1 = AudioURLfloor2;
        }
        if (Application.loadedLevelName == "floor3")
        {
            clip1 = AudioURLfloor3;
        }
        if (Application.loadedLevelName == "floor4") {
			if (PlayerPrefs.GetInt ("Posters") == 0) {
				clip1 = AudioURLfloor4_1;
			}
			if (PlayerPrefs.GetInt ("Posters") == 1) {
				clip1 = AudioURLfloor4_2;
			}
			if (PlayerPrefs.GetInt ("Posters") == 2) {
				clip1 = AudioURLfloor4_3;
			}
			clip2 = AudioURLEnd;
		}
    }
    void Update () {
        if (FPSTimer >= 0) {
            FPSTimer -= Time.deltaTime;
            FPSCounter++;
        }
        else {
            FPSData += ""+(FPSCounter/30f)+" ";
            FPSTimer = 30f;
            FPSCounter = 0;
        }
        if (audioTimer >= 0){
            audioTimer -= Time.deltaTime;
        }
        if (audioTimer < 0 && audioTimer != -99){
			AudioSource source = GetComponent<AudioSource> ();
			source.clip = clip1;
			source.Play ();
			audioTimer = -99;
        }
        timer -= Time.deltaTime;
        if ((timer <= 0 && !levelEnding) || (Input.GetButtonDown("Skip") && !levelEnding)){
            print("ending");
            StartCoroutine(EndLevel());
        }
		locationTimer -= Time.deltaTime;
		if (locationTimer < 0){
			locationData += "" + player.transform.position + ",";
			locationTimer = 0.5f;
		}
    }
	IEnumerator EndLevel() {
		print ("level ending");

		levelEnding = true;
        playerGUI.paused = true;
        Time.timeScale = 0;
        
		WWWForm form = new WWWForm();

        form.AddField("ID", PlayerPrefs.GetString("PlayerID"));
        form.AddField( "Posters", PlayerPrefs.GetInt ("Posters") );
		form.AddField( "Level", SceneManager.GetActiveScene().name );
		form.AddField( "Shots", PlayerPrefs.GetInt ("Shots") );
		form.AddField( "Hits", PlayerPrefs.GetInt ("Hits") );
		form.AddField( "Damage", PlayerPrefs.GetInt ("Damage") );
		form.AddField( "Deaths", PlayerPrefs.GetInt ("Deaths") );
		form.AddField( "Kills", PlayerPrefs.GetInt ("Kills") );

        float totalTimeCenter = 0;
        float totalTimePeriphery = 0;
        float totalSizeCenter = 0;
        float totalSizePeriphery = 0;
        int totalGlances = 0;
        var foundObjects = FindObjectsOfType<DataTrackingObject>();
        foreach (DataTrackingObject item in foundObjects) {
            totalTimeCenter += item.timeCenter;
            totalTimePeriphery += item.timePeriphery;
            totalSizeCenter += item.sizeCenter;
            totalSizePeriphery += item.sizePeriphery;
            totalGlances += item.glances;
        }
        totalSizeCenter /= 1000f;
        totalSizePeriphery /= 1000f;

        form.AddField("Time_Center", totalTimeCenter+"");
        form.AddField("Time_Periphery", totalTimePeriphery + "");
        form.AddField("Size_Center", totalSizeCenter + "");
        form.AddField("Size_Periphery", totalSizePeriphery + "");
        form.AddField("Number_of_Glances", totalGlances + "");
        form.AddField("Avg_FPS", FPSData + "");

        Dictionary<string, string> headers = form.headers;
		headers.Add("Authorization", "Token rpYneBdy24YDhJe2");
		byte[] rawData = form.data;

		WWW www = new WWW("https://cnburrows.com/web_exp/datawrite.php", rawData, headers);

		yield return www;
        if (nextLevel != "")
        {
            StartCoroutine(LoadYourAsyncScene());
        }
        else{
            Application.OpenURL("https://tamu.qualtrics.com/jfe/form/SV_5ikoi8ghnu39pk1?MTurkID=" + PlayerPrefs.GetString("PlayerID") + "&C=" + PlayerPrefs.GetInt("Posters"));
        }
    }
    IEnumerator LoadYourAsyncScene()
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(nextLevel);
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }
}
