﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.Json;
using SimpleJSON;

public static class PlayfabCloudScriptAPI {

    public static void LogErrorToServer(string _message) {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "logError", 
            FunctionParameter = new {
                message = _message
            },
            GeneratePlayStreamEvent = true, // REMOVE?
        }, OnSuccessCallback, OnErrorShared);
    }

    public static void AfterRegistration(string referredBy) {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "afterRegistration", // Function name to be used in Cloud Script handles.createNewTeacherAlphaMatch
            FunctionParameter = new {
                referred_by = referredBy
            }, // The parameter provided to your function
            GeneratePlayStreamEvent = true, // Optional - Shows this event in PlayStream
        }, OnSuccessfulShare, OnErrorShared);
    }

    private static void OnSuccessfulShare(ExecuteCloudScriptResult result) {
        // Cloud Script returns arbitrary results, so you have to evaluate them one step and one parameter at a time
        DebugChannelSO.OverrideRaise(
            "PlayfabCloudScriptAPI",
            "You were referred!",
            new Color(1, 0.5f, 0.1f));
    }

    public static void SetCurrentPlayerAsCreatorCorps() {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "setCurrentPlayerAsCreatorCorps",
            FunctionParameter = new {

            },
            GeneratePlayStreamEvent = true,
        }, OnSuccessCallback, OnErrorShared);
    }

    public static void UpdatePlayerMoodleData(string moodleUsername) {
        if (moodleUsername == null) {
            return;
        }

        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "updatePlayerMoodleData",
            FunctionParameter = new {
                moodle_username = moodleUsername,
            },
            GeneratePlayStreamEvent = true,
        }, OnSuccessCallback, OnErrorShared);
    }

    private static void OnSuccessCallback(ExecuteCloudScriptResult result) {
        DebugChannelSO.OverrideRaise(
            "PlayfabCloudScriptAPI",
            result.FunctionResult.ToString(),
            new Color(1, 0.5f, 0.1f));
    }

    private static void OnErrorShared(PlayFabError error) {
        DebugChannelSO.OverrideRaise(
            "PlayfabCloudScriptAPI",
            new string[]
            {
                "Error from PlayfabCloudScriptAPI.OnErrorShared",
                error.GenerateErrorReport()
            },
            new Color(1, 0.5f, 0.1f),
            DebugChannelSO.Severity.Error);

        WriteToLog(error.GenerateErrorReport());
    }
    public static void WriteToLog(string message)
    {
    #if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN
        // We only create files on desktop versions
        LogToFileOnSystem(message, UnityEngine.StackTraceUtility.ExtractStackTrace());
    #endif

        DebugChannelSO.OverrideRaise(
            "PlayfabCloudScriptAPI", 
            message, 
            new Color(1, 0.5f, 0.1f));
    }

#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN
    static void LogToFileOnSystem(string message, string stackTrace)
    {
        string path = Path.Combine(Environment.CurrentDirectory, "log.txt");

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Welcome to the error log!");
                sw.WriteLine("");
            }
        }

        using (StreamWriter sw = File.AppendText(path))
        {
            //if (PersistentData.localPlayerData.playFabId != null) {
            //    sw.WriteLine("ID: " + PersistentData.localPlayerData.playFabId);
            //}
            sw.WriteLine("UTC: " + DateTime.UtcNow);
            sw.WriteLine(message);
            sw.WriteLine(stackTrace);
            sw.WriteLine();
        }
    }
#endif

    public static void SetCompletedMatch(int completedMatches) {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "setCompletedMatches",
            FunctionParameter = new {
                completed_matches = completedMatches
            },
            GeneratePlayStreamEvent = true,
        }, OnSuccessfulSomething, OnErrorShared);
    }

    public static void SetWins(int wins) {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "setWins",
            FunctionParameter = new {
                win_number = wins
            },
            GeneratePlayStreamEvent = true,
        }, OnSuccessfulSomething, OnErrorShared);
    }

    public static void SetDefeats(int defeats) {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
            FunctionName = "setDefeats",
            FunctionParameter = new {
                defeat_number = defeats
            },
            GeneratePlayStreamEvent = true,
        }, OnSuccessfulSomething, OnErrorShared);
    }

    private static void OnSuccessfulSomething(ExecuteCloudScriptResult result) {
        //Debug.Log("You have partaken in a match or level and may or may not have completed it!");
    }
}

