<?php

namespace App\Http\Controllers\Game;

use App\Game\GameCard;
use App\Http\Controllers\Controller;
use App\Models\Treasure\GameScoreLocker;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class HallApiController extends Controller
{
    public function index()
    {

    }
    private function checkAuth(Request $request)
    {
        Util::WriteLog("hallapi","");
        return $request->input('pass','')=='24680.com';
    }
    public function SetIngameState(Request $request)
    {
        if(!$this->checkAuth($request))return;
        $UserID=$request->input('UserID')??null;

        $redisKey='SetIngameState_'.$UserID;
        $n=0;
        while (!SetNXLock::getExclusiveLock($redisKey)){
            sleep(1);
            $n++;
            if($n>3){
                break;
            }
        }

        $GlobalUID=$request->input('GlobalUID')??null;
        $ingame_state=$request->input('ingame_state')??"0";
        $ingame_state=intval($ingame_state);
        $key='ingame_state_'.$UserID;

        if($ingame_state!=-1) {
            Redis::set($key, $ingame_state);
            if($ingame_state>0){
                GameCard::$enableStateCheck=false;
                $game=GameCard::where('id',$ingame_state)->first();
                //ouro777的游戏，不管
                if(isset($game)&&!in_array($game->brand,['OURO777','PGSoft'])){
//                    $ingame=GameScoreLocker::where('UserID',$UserID)->exists();
                    GameScoreLocker::updateOrInsert(['UserID'=>$UserID],[
                        'UserID'       => $UserID,
                        'KindID'       => 0,
                        'ServerID'     => $ingame_state,
                        'EnterID'      => 0,
                        'EnterIP'      => $request->input('ip') ?? '',
                        'ByHallServer' => 1
                    ]);
                }
            }else{
                GameScoreLocker::where('ByHallServer',1)->where('UserID',$UserID)->delete();
            }
        }else{
            Redis::del($key);
            GameScoreLocker::where('ByHallServer',1)->where('UserID',$UserID)->delete();
        }
        SetNXLock::release($redisKey);

        exit("");
    }
    public function ClearLocker(Request $request)
    {
        if(!$this->checkAuth($request))return;
        GameScoreLocker::where('ByHallServer',1)->delete();
        exit("");
    }
}
