package com.example.demo.module.login;

import com.example.demo.common.GlobalRoot;
import com.example.demo.table.UserLogin;
import com.example.demo.table.user.UserInfo;
import org.springframework.stereotype.Repository;
import pers.jc.sql.SQL;
import pers.jc.sql.Transaction;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 仓库-游戏登录
 */
@Repository
public class GameLoginRepository {

    public UserLogin getUserLogin(String username) {
        return GlobalRoot.db.selectOne(UserLogin.class, new SQL(){{
            WHERE("username=" + PARAM(username));
        }});
    }

    public UserLogin getUserLogin(int id) {
        return GlobalRoot.db.selectOne(UserLogin.class, new SQL(){{
            WHERE("id=" + PARAM(id));
        }});
    }

    public int updateUserLogin(UserLogin userLogin) {
        return GlobalRoot.db.update(userLogin);
    }

    public boolean insertNewUser(UserLogin userLogin, String email, String phone) {
        UserInfo userInfo = new UserInfo();
        userInfo.setEmail(email == null ? "" : email);
        userInfo.setPhone(phone == null ? "" : phone);
        return insertNewUser(userLogin, userInfo);
    }

    public boolean insertNewUser(UserLogin userLogin, UserInfo userInfo) {
        AtomicBoolean done = new AtomicBoolean();
        new Transaction(GlobalRoot.db.getAccess()){
            @Override
            public void run() throws Exception {
                insertAndGenerateKeys(userLogin);
                if (userLogin.getId() == 0) return;
                userInfo.setId(userLogin.getId());
                insert(userInfo);
                commit();
            }
            public void success() {
                done.set(true);
            }
        };
        return done.get();
    }

    public UserInfo getUserInfo(int id) {
        return GlobalRoot.db.selectOne(UserInfo.class, new SQL(){{
            WHERE("id=" + PARAM(id));
        }});
    }

    public int updateUserInfo(UserInfo userInfo) {
        return GlobalRoot.db.update(userInfo);
    }

    public void setUserOfflineTime(int userID) {
        GlobalRoot.db.update(new SQL(){{
            UPDATE("user_info");
            SET("offlineTime = " + System.currentTimeMillis());
            WHERE("id = " + userID);
        }});
    }
}
