package com.example.demo.module.user;

import com.example.demo.common.GlobalRoot;
import com.example.demo.table.*;
import com.example.demo.table.user.DeviceInfo;
import com.example.demo.table.user.UserInfo;
import pers.jc.network.SocketComponent;
import pers.jc.network.SocketMethod;
import pers.jc.network.SocketResponse;
import pers.jc.sql.SQL;
import pers.jc.sql.Transaction;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Socket组件-用户
 */
@SocketComponent("userComp")
public class UserComp {

    @SocketMethod(async = true)
    public void getUserInfo(Player player, SocketResponse response) {
        response.send(getUserInfo(player.userID));
    }

    public static UserInfo getUserInfo(int uid) {
        UserInfo userInfo = GlobalRoot.db.selectOne(UserInfo.class, new SQL(){{
            WHERE("id=" + PARAM(uid));
        }});
        if (userInfo != null && userInfo.getDeviceList().size() == 0) {
            //因为一开始没有设备，所以先赋予两套，分别为弓和箭
            int[] ids = {1000, 2000};
            for (int id : ids) {
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.id = id;
                deviceInfo.inuse = true;
                userInfo.getDeviceList().add(deviceInfo);
            }
        }
        return userInfo;
    }

    @SocketMethod(async = true)
    public void saveUserInfo(Player player, UserInfo userInfo) {
        if (userInfo.getId() == player.userID) {
            GlobalRoot.db.update(userInfo);
        }
    }

    @SocketMethod(async = true)
    public void saveMac(Player player, String mac, SocketResponse response) {
        if (mac == null) return;
        mac = mac.trim();
        final String mac0 = mac;
        GlobalRoot.db.update(new SQL(){{
            UPDATE(UserInfo.class);
            SET("mac = " + PARAM(mac0));
            WHERE("id = " + player.userID);
        }});
        MacCalibrate macCalibrate = GlobalRoot.db.selectOne(MacCalibrate.class, new SQL(){{
            WHERE("mac = " + PARAM(mac0));
        }});
        if (macCalibrate != null) {
            response.send(macCalibrate);
        }
    }

    @SocketMethod(async = true)
    public void saveMacCalibrate(int type, String mac, String record) {
        if (mac == null) return;
        mac = mac.trim();
        if (record == null) return;

        //某个弃用的ios版本会上传脏数据，避免数据库被脏数据覆盖
        if (type == 1 && !record.contains("CorrectMatrixArray")) return;

        final String mac0 = mac;
        MacCalibrate macCalibrate = GlobalRoot.db.selectOne(MacCalibrate.class, new SQL(){{
            WHERE("mac = " + PARAM(mac0));
        }});
        if (macCalibrate == null) {
            macCalibrate = new MacCalibrate();
            macCalibrate.setMac(mac);
        }
        if (type == 0) macCalibrate.setGyr(record);
        if (type == 1) macCalibrate.setMag(record);
        GlobalRoot.db.replace(macCalibrate);
    }

    @SocketMethod(async = true)
    public void saveMac2(Player player, String mac, int type) {
        if (mac == null) return;
        mac = mac.trim();

        final String mac0 = mac;
        GlobalRoot.db.update(new SQL(){{
            UPDATE(UserInfo.class);
            SET("mac = " + PARAM(mac0));
            WHERE("id = " + player.userID);
        }});

        String record = null;
        if (type == 9) {
            Mac9Axis model = GlobalRoot.db.selectOne(Mac9Axis.class, new SQL(){{
                WHERE("mac = " + PARAM(mac0));
            }});
            if (model != null) record = model.getAttitude();
        }
        else if (type == 663) {
            Mac663Axis model = GlobalRoot.db.selectOne(Mac663Axis.class, new SQL(){{
                WHERE("mac = " + PARAM(mac0));
            }});
            if (model != null) record = model.getAttitude();
        }
        if (record != null) {
            player.call("UserComp.onResumeCalibrateRecord", record);
        }
    }

    /**
     * 2023/1/10 弃用该旧版接口
     */
    @SocketMethod(async = true)
    public void saveCalibrateRecord(Player player, int type, String record, String mac) {
        if (type == 9) {
            player.call("onAnyMessage", "（服务端反馈）旧数据有高低位问题不再保存,九轴数据保存失败");
            return;
        }
        if (type == 663) {
            player.call("onAnyMessage", "（服务端反馈）旧数据有高低位问题不再保存,663轴数据保存失败");
            return;
        }
    }

    /**
     * 2023/1/10 保存校准数据
     */
    @SocketMethod(async = true)
    public void saveCalibrateRecord2(Player player, int type, String record, String mac) {
        if (record == null) return;
        if (mac == null) return;
        mac = mac.trim();

        if (type == 9) {
            Mac9Axis model = new Mac9Axis();
            model.setMac(mac);
            model.setAttitude(record);
            int res = GlobalRoot.db.replace(model);
            player.call("onAnyMessage", "（服务端反馈）九轴数据保存" + (res > 0 ? "成功" : "失败"));
            return;
        }

        if (type == 663) {
            Mac663Axis model = new Mac663Axis();
            model.setMac(mac);
            model.setAttitude(record);
            GlobalRoot.db.replace(model);
            return;
        }
    }

    @SocketMethod(async = true)
    public void saveGuideRecord(Player player, String str) {
        char[] chars = str.toCharArray();
        for (char aChar : chars) {
            if (!(aChar == '0' || aChar == '1')) {
                return;
            }
        }
        GlobalRoot.db.update(new SQL(){{
            UPDATE(UserInfo.class);
            SET("guideRecord = " + PARAM(str));
            WHERE("id = " + player.userID);
        }});
    }

    /**
     * 删除账号
     */
    @SocketMethod(async = true)
    public void deleteAccount(Player player, SocketResponse response) {
        int uid = player.userID;
        AtomicBoolean done = new AtomicBoolean();
        new Transaction(GlobalRoot.db.getAccess()){
            @Override
            public void run() throws Exception {
                delete(new SQL(){{
                    DELETE_FROM(UserLogin.class);
                    WHERE("id = " + PARAM(uid));
                }});
                delete(new SQL(){{
                    DELETE_FROM(UserInfo.class);
                    WHERE("id = " + PARAM(uid));
                }});
                commit();
            }
            @Override
            public void success() {
                done.set(true);
                System.out.println("用户删除成功，ID:" + uid);
            }
        };
        response.send(done.get());
    }

    /**
     * 删除账号
     */
    @SocketMethod(async = true)
    public void deleteAccountByApple(Player player, String record, SocketResponse response) {
        int uid = player.userID;
        AtomicBoolean done = new AtomicBoolean();
        new Transaction(GlobalRoot.db.getAccess()){
            @Override
            public void run() throws Exception {
                delete(new SQL(){{
                    DELETE_FROM(UserLogin.class);
                    WHERE("id = " + PARAM(uid));
                }});
                delete(new SQL(){{
                    DELETE_FROM(UserInfo.class);
                    WHERE("id = " + PARAM(uid));
                }});
                commit();
            }
            @Override
            public void success() {
                done.set(true);
                System.out.println("用户删除成功，ID:" + uid);
            }
        };
        response.send(done.get());
    }
}
