package com.example.demo.module.heart_rate_band;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.GlobalRoot;
import com.example.demo.common.RequestResult;
import com.example.demo.module.heart_rate_band.dto.HRB_UserInfoA;
import com.example.demo.module.login.GameLoginRepository;
import com.example.demo.module.login.LoginToken;
import com.example.demo.module.user.Player;
import com.example.demo.table.UserLogin;
import com.example.demo.table.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.jc.network.SocketMethod;
import pers.jc.sql.SQL;

@CrossOrigin
@RestController
@RequestMapping("/hrb")
public class HRBController {
    @Autowired
    GameLoginRepository service;

    @PostMapping("/getUserInfo")
    public RequestResult getUserInfo(String token)
    {
        RequestResult requestResult = new RequestResult();
        requestResult.setCode(-1);
        LoginToken loginToken = LoginToken.parseClientToken(token);
        if (loginToken == null) return requestResult;
        UserLogin userLogin = service.getUserLogin(loginToken.uid);
        if (userLogin == null) return requestResult;
        if (!userLogin.getToken().equals(loginToken.getLoginTokenForDatabase())) return requestResult;
        HRB_UserInfoA userInfo = GlobalRoot.db.selectOne(HRB_UserInfoA.class, new SQL(){{
            WHERE("id=" + PARAM(userLogin.getId()));
        }});
        if (userInfo == null) return requestResult;
        requestResult.setCode(0);
        requestResult.setData(userInfo);
        return requestResult;
    }

    @PostMapping("/saveUserInfo")
    public RequestResult saveUserInfo(String token, String userInfoJSON) {
        HRB_UserInfoA userInfo = JSON.parseObject(userInfoJSON, HRB_UserInfoA.class);
        RequestResult requestResult = new RequestResult();
        requestResult.setCode(-1);
        LoginToken loginToken = LoginToken.parseClientToken(token);
        if (loginToken == null) return requestResult;
        UserLogin userLogin = service.getUserLogin(loginToken.uid);
        if (userLogin == null) return requestResult;
        if (!userLogin.getToken().equals(loginToken.getLoginTokenForDatabase())) return requestResult;
        if (userInfo == null) return requestResult;
        if (userLogin.getId() != userInfo.getId()) return requestResult;
        GlobalRoot.db.update(userInfo);
        requestResult.setCode(0);
        return requestResult;
    }
}
