using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame.Net
{
///
/// 서버와 기기 상태를 맞추는 일꾼(서버 모드에서 세션마다 1개).
/// 1. 접속: 서버 상태 확인 → 기준 정보(재화 목록) → 로그인 → 계정 수신 — 끝날 때까지 화면을 막는다.
/// 2. 전송: 기기에서 이미 반영한 동작을 **순서대로 하나씩** 서버에 보낸다(줄 세우기).
/// 3. 맞춤: 보낼 것이 없어지면 서버의 계정 상태를 다시 받아 기기 값을 덮는다 — 서버가 정본이다.
/// 4. 거절: 서버가 요청을 받아 주지 않으면(기기와 서버가 어긋남) 남은 요청을 버리고 서버 상태로 되돌린다.
/// 5. 끊김: 연결 문제는 몇 번 조용히 다시 보내고, 그래도 안 되면 화면을 막고 「다시 시도」를 받는다.
///
public class ServerSync : MonoBehaviour
{
public static ServerSync Instance { get; private set; }
public ServerClient Client { get; private set; }
/// 접속이 끝나 계정 상태를 받았는가.
public bool Ready { get; private set; }
/// 보내는 중이거나 보낼 것이 남았는가.
public bool Busy
{
get { return sending || queue.Count > 0; }
}
/// 서버 상태로 맞춘 횟수(접속 때 1회 제외).
public int Reconciles { get; private set; }
/// 서버가 거절한 횟수.
public int Rejects { get; private set; }
public string LastError { get; private set; }
/// 화면을 막는 안내가 떠 있는가.
public bool Blocking
{
get { return overlay != null && overlay.activeSelf; }
}
class Item
{
public string method;
public string path;
/// 보내는 순간에 만든다(앞 요청의 응답 값 — 예: 전투 세션 — 을 쓸 수 있게).
public Func body;
public Action onOk;
public Action onReject;
/// 응답이 와야 화면을 채울 수 있는 요청(전투 종료 · 등용 · 상자 열기 …) — 오래 걸리면 안내를 띄운다.
public bool wait;
/// 응답을 받은 직후 서버의 계정 상태로 기기 값을 먼저 맞춘 다음 onOk 를 부른다(결과를 서버가 정하는 동작 — 화면이 맞춰진 값을 읽게).
public bool syncAfter;
/// 거절이 「기기와 서버가 어긋난 것」이 아닌 요청(쿠폰 코드 틀림 · 우편함 조회 …) — 거절돼도 뒤 요청을 버리지 않고 안내도 띄우지 않는다.
public bool soft;
}
readonly Queue queue = new Queue();
ServerSession session;
bool sending;
bool dirty;
float reconcileAt;
bool retryPressed;
float waitSince = -1f;
// 서버가 주간 랭킹 정산 중이라 입장을 거절했을 때의 이유 코드
const string SettleCode = "RANK_SETTLING";
// 안내 캔버스 = 다른 모든 화면(재화 바 450 · 타이틀 전환 960) 위 · 카메라에 가장 가까운 면
const int OverlayOrder = 990;
const float OverlayPlane = 0.3f;
GameObject overlay;
Text overlayText;
GameObject overlayButton;
internal static ServerSync Create(ServerSession session)
{
if (Instance != null) Destroy(Instance.gameObject); // 씬을 다시 연 경우 — 앞 세션의 일꾼을 치운다
var go = new GameObject("ServerSync");
var s = go.AddComponent();
s.session = session;
s.Client = new ServerClient(ServerConfig.BaseUrl, ServerConfig.TimeoutSec, !ServerConfig.Forced);
Instance = s;
s.StartCoroutine(s.Run());
return s;
}
void OnDestroy()
{
if (Instance == this) Instance = null;
}
/// 요청을 줄 맨 뒤에 세운다. onReject = 서버가 거절했거나, 앞 요청이 거절돼 보내지 못하고 버려졌을 때.
internal void Post(string method, string path, Func body, Action onOk = null, Action onReject = null, bool wait = false, bool syncAfter = false, bool soft = false)
{
queue.Enqueue(new Item { method = method, path = path, body = body, onOk = onOk, onReject = onReject, wait = wait, syncAfter = syncAfter, soft = soft });
}
/// 보낼 것이 없어도 서버의 계정 상태를 한 번 다시 받는다(연무장 화면을 열 때 — 날짜 · 시즌이 넘어갔으면 서버가 맞춘 값이 온다).
internal void Refresh()
{
dirty = true;
reconcileAt = 0f;
}
IEnumerator Run()
{
yield return Connect();
while (true)
{
if (queue.Count == 0)
{
if (dirty && Time.unscaledTime >= reconcileAt) yield return Reconcile();
yield return null;
continue;
}
yield return SendNext();
}
}
// ---------- 접속 ----------
IEnumerator Connect()
{
var r = new ServerResult();
while (true)
{
ShowOverlay("서버에 접속하는 중…", false);
yield return Client.Send("GET", "/games/" + ServerConfig.GameId + "/status", null, false, r);
if (!r.ok)
{
yield return AskRetry("서버에 접속할 수 없습니다", r);
continue;
}
if (r.Str("status") != "NORMAL")
{
yield return AskRetry("서버 점검 중입니다 (" + r.Str("status") + ")", null);
continue;
}
yield return Client.Send("GET", "/tks/config", null, false, r);
if (!r.ok || !session.LoadGoodsTable(r))
{
yield return AskRetry("서버 기준 정보를 받지 못했습니다", r);
continue;
}
yield return Client.Login(ServerConfig.GameId, r);
if (!r.ok)
{
yield return AskRetry("로그인하지 못했습니다", r);
continue;
}
// 기기 시간대를 실어 보낸다 — 새 계정이면 서버가 이때 계정에 고정한다(일일 초기화 = 그 나라 0시)
yield return Client.Send("GET", ServerSession.AccountPath(), null, true, r);
if (!r.ok)
{
yield return AskRetry("계정 정보를 받지 못했습니다", r);
continue;
}
session.ApplySnapshot(r, true);
Ready = true;
HideOverlay();
yield break;
}
}
// ---------- 전송 ----------
IEnumerator SendNext()
{
var it = queue.Peek();
sending = true;
var r = new ServerResult();
int tries = 0;
if (it.wait) waitSince = Time.unscaledTime;
while (true)
{
yield return Client.Send(it.method, it.path, it.body != null ? it.body() : null, true, r);
if (r.ok || !r.network) break;
if (tries < ServerConfig.Retry)
{
tries++;
yield return new WaitForSecondsRealtime(0.5f * tries);
continue;
}
yield return AskRetry("서버와 연결이 끊겼습니다", r); // 「다시 시도」 = 같은 요청을 다시 보낸다
tries = 0;
}
waitSince = -1f;
HideOverlay();
queue.Dequeue();
sending = false;
if (r.ok)
{
if (it.syncAfter)
{
sending = true; // 맞추는 동안도 「보내는 중」
if (it.wait) waitSince = Time.unscaledTime;
yield return Reconcile(true);
waitSince = -1f;
HideOverlay();
sending = false;
}
if (it.onOk != null) it.onOk(r);
dirty = true;
reconcileAt = Time.unscaledTime + ServerConfig.ReconcileDelay;
yield break;
}
if (it.soft)
{
// 어긋난 것이 아닌 거절(쿠폰 코드 틀림 등) — 그 요청만 실패로 알리고 줄은 그대로 둔다
if (it.onReject != null) it.onReject(r);
yield break;
}
// 서버가 거절 = 기기와 서버가 어긋났다 → 뒤에 줄 선 요청은 어긋난 상태에서 만든 것이라 버리고 서버 상태로 되돌린다
Rejects++;
LastError = it.method + " " + it.path + " → " + r.error;
Debug.LogWarning("[TKS] 서버가 요청을 거절했습니다: " + LastError);
var dropped = queue.ToArray();
queue.Clear();
if (it.onReject != null) it.onReject(r);
foreach (var d in dropped)
if (d.onReject != null) d.onReject(r);
dirty = true;
reconcileAt = 0f;
yield return Reconcile();
Notice(r.Message == SettleCode ? ArenaRules.SettleNotice : "서버 기록과 달라 다시 불러왔습니다 (" + r.Message + ")");
}
/// 서버의 계정 상태로 기기 값을 덮는다. 받는 사이에 새 요청이 줄 섰으면 버리고 다음에 다시 한다(force = 줄이 있어도 덮는다).
IEnumerator Reconcile(bool force = false)
{
var r = new ServerResult();
yield return Client.Send("GET", "/tks/account", null, true, r);
if (!r.ok)
{
reconcileAt = Time.unscaledTime + Mathf.Max(1f, ServerConfig.ReconcileDelay) * 3f; // 조금 뒤에 다시
yield break;
}
if (queue.Count > 0 && !force) yield break;
session.ApplySnapshot(r, false);
dirty = false;
Reconciles++;
}
void Update()
{
// 응답을 기다려야 하는 요청이 오래 걸리면 안내
if (waitSince >= 0f && !Blocking && Time.unscaledTime - waitSince >= ServerConfig.WaitNotice) ShowOverlay("서버에 기록하는 중…", false);
}
// ---------- 안내 ----------
static void Notice(string msg)
{
if (OutGameRoot.Instance != null) OutGameRoot.Instance.Toast(msg);
}
IEnumerator AskRetry(string msg, ServerResult r)
{
LastError = msg + (r != null && !string.IsNullOrEmpty(r.error) ? " — " + r.error : "");
Debug.LogWarning("[TKS] " + LastError);
retryPressed = false;
ShowOverlay(msg + (r != null && !string.IsNullOrEmpty(r.error) ? "\n" + r.error + "" : ""), true);
while (!retryPressed) yield return null;
}
/// 「다시 시도」 누름(화면 버튼 · 테스트).
public void PressRetry()
{
retryPressed = true;
}
void ShowOverlay(string msg, bool button)
{
if (overlay == null) BuildOverlay();
overlayText.text = msg;
overlayButton.SetActive(button);
overlay.SetActive(true);
}
void HideOverlay()
{
if (overlay != null) overlay.SetActive(false);
}
/// 화면 전체를 덮어 누름을 막는 안내(가끔만 뜨고 평소엔 꺼 둔다 · 자기 캔버스 1개 = 사건 때만 바뀌는 층).
void BuildOverlay()
{
overlay = new GameObject("ServerOverlay");
overlay.transform.SetParent(transform, false);
var cam = OutGameRoot.Instance != null && OutGameRoot.Instance.Cam != null ? OutGameRoot.Instance.Cam : Camera.main;
UiLayer.Root(overlay, cam, OverlayOrder, OverlayPlane, OutGameRoot.Reference, UiRate.Event);
var dim = UiKit.Fill("Dim", overlay.transform);
var img = dim.gameObject.AddComponent();
img.color = new Color(0f, 0f, 0f, 0.72f);
img.raycastTarget = true; // 아래 화면 누름 막기
var center = new Vector2(0.5f, 0.5f);
overlayText = UiKit.Label(dim, "", 36, Color.white, TextAnchor.MiddleCenter, center, center, new Vector2(0f, 60f), new Vector2(900f, 260f));
overlayText.supportRichText = true;
var btn = new GameObject("Retry", typeof(RectTransform), typeof(Image), typeof(Button));
btn.transform.SetParent(dim, false);
var rt = (RectTransform)btn.transform;
rt.anchorMin = rt.anchorMax = rt.pivot = center;
rt.anchoredPosition = new Vector2(0f, -150f);
rt.sizeDelta = new Vector2(360f, 110f);
btn.GetComponent().color = UiKit.Red;
btn.GetComponent