using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using TMPro; using UnityEngine; using UnityEngine.UI; public class SaveHistoryData : MonoBehaviour { [SerializeField] private TextMeshProUGUI _dateText; [SerializeField] private TextMeshProUGUI _sourceText; private string _source; private DateTime _date; static private bool _isProcessing; public bool IsFromServer; public void SetValues(string date, string source, bool isFromServer) { SetDate(date); SetSource(source); IsFromServer = isFromServer; } private void SetDate(string date) { _date = GetDateTime(date); string finalDate = _date.ToString("d MMMM yyyy"); string finalTime = _date.ToString("HH:mm"); _dateText.text = finalDate + "\n" + finalTime; } private void SetSource(string source) { _source = source; _sourceText.text = _source; } static public DateTime GetDateTime(string date) { string[] dateInfo = date.Split("_"); string year_month_day = dateInfo[0]; string hour_minute = dateInfo[1]; int year = int.Parse(year_month_day[..4]); int month = int.Parse(year_month_day[4..6]); int day = int.Parse(year_month_day[6..]); int hour = int.Parse(hour_minute[..2]); int minute = int.Parse(hour_minute[2..]); return new DateTime(year, month, day, hour, minute, 0); } // Used on UI elements to load save files from server public void LoadSaveFile(bool bypassProcessing = false) { if (_isProcessing && !bypassProcessing) { return; } _isProcessing = true; if (IsFromServer) { SaveHistoryData lastestSave = transform.parent.GetChild(0).GetComponent(); if (!lastestSave.IsFromServer) { StartCoroutine(lastestSave.SaveThenLoad(this)); } else { StartCoroutine(LoadHistory.Instance.RequestLoadFromServer(PostLoadSaveAction.data, _date, OnLoadCallback)); } } else { SetSource("Saving to server...\nLocal"); IsFromServer = true; byte[] bytes = SaveXML.BuildXmlBytes(); string xmls = Encoding.UTF8.GetString(bytes); StartCoroutine(LoadHistory.Instance.RequestAutoSaveToServer(xmls, OnSaveCallback)); } } private void OnLoadCallback() { _isProcessing = false; } private void OnSaveCallback(bool isSuccess) { IsFromServer = isSuccess; _isProcessing = false; BackgroundSave.Instance.ResetTimer(); if (isSuccess) { SetSource("Saved\nServer"); } else { SetSource("Failed to save\nLocal"); } } public IEnumerator SaveThenLoad(SaveHistoryData loadSave) { Debug.Log("Saving current scene before loading next one"); LoadSaveFile(true); while (_isProcessing) { yield return null; } if (IsFromServer) { Debug.Log("Saved to server, loading other save file..."); loadSave.LoadSaveFile(); } else { Debug.Log("Could not save to server"); } } // Workaround to scroll through save history while pointer is on UI elements that block raycasts public void OnScroll() { GetComponent().raycastTarget = false; Invoke(nameof(ScrollDisable), 0.1f); } private void ScrollDisable() { GetComponent().raycastTarget = true; } }