import io from 'socket.io-client'
import PubSub from 'pubsub-js';

// const [isConnected, setIsConnected] = useState(socket.connected);
// const [fooEvents, setFooEvents] = useState([]);

class AccountAuth {
    constructor(){
        const URL = '121.42.8.157:19702'
        this._socket = io(URL, {
            transports: ["websocket", "polling"],
            // path: '',
            autoConnect: true,
        });

        // console.log("AccountAuth connected", this._socket.connected, this._socket);

        this._socket.on('connect', this.onConnect);
        this._socket.on('connect_error', this.onError);
        this._socket.on('error', this.onError);
        this._socket.on('connect_timeout', this.onTimeout);
        this._socket.on('disconnect', this.onDisconnect);

        this.authed = false;
    }
    
    onConnect = () => {
        // console.log("connected");
        this._socket.emit(
            "USER",
            {
                cmd: "login",
                data: {
                    user_name: "zjs",
                    user_pass: "123",
                },
            }, (data) => {
                // console.log("OK, got into login-callback");
                // console.log(JSON.stringify(data));
            }
        );

        setTimeout(() => {
            let token = localStorage.getItem("user_token");
            if(token){
                var sql = `SELECT 
                            user_id,
                            user_name,
                            user_account
                        FROM 
                            medba.dat_user 
                        WHERE 
                            user_token = '${token}'`;
                var msg = {
                    cmd: "query", // server端要进行判断的
                    data: {
                    name: "name", // 这个无所谓怎么写，有就行
                    sql: sql,
                    },
                };
                this._socket.emit("REPT", msg, (datas) => {
                    if(datas.data.length > 0){
                        let user_id = datas.data[0].user_id;
                        this.authed = true;
                        this.getMapData(user_id);
                        window.editor_user = {
                            id: user_id,
                            account: datas.data[0].user_account,
                            token: token,
                            name: datas.data[0].user_name,
                            auth: window.editor_user_auth,
                            edit_map: 0,
                            maps: []
                        };

                        /**
                         * Event when user has been successfully logged in
                         * @event app.user.ready
                         * @memberof App
                         */
                        PubSub.publish("app.user.ready", { username: window.editor_user.name });
                        console.log("Logged in as", window.editor_user.name);
                        this.authed = true;
                    }
                });
            }else {
                console.log("no token");
            }
        }, 100);
    }
    
    onError(e) {
        console.log("error", e);
    }
    
    onTimeout(e) {
        console.log("timeout", e);
    }

    onDisconnect(e) {
        console.log("disconnected", e);
    }

    authenticated(){
        return this.authed;
    }

    authenticate(data, auth){
        var sql = `SELECT 
                        * 
                    FROM 
                        medba.dat_user 
                    WHERE 
                        user_name = '${data.account}' AND 
                        user_password = '${data.password}'`;
        var msg = {
            cmd: "query", // server端要进行判断的
            data: {
              name: "name", // 这个无所谓怎么写，有就行
              sql: sql,
            },
          };
        this._socket.emit("REPT", msg, (datas) => {
            console.log(datas.data);
            if(datas.data.length === 1){
                this.authed = true;
                // console.log('ok authenticated ', this.authed);
                auth(undefined, datas.data[0]);
                this._setLogin(datas.data[0]);
            } else {
                alert('请检查账号密码是否有错误。');
            }
        });
    }

    _setLogin(data){
        var sql = `UPDATE medba.dat_user 
                    SET 
                        last_login_time = NOW() 
                    WHERE 
                        user_id = ${data.user_id}`;
        var msg = {
            cmd: "update", // server端要进行判断的
            data: {
                op: "UPDATE", // INSERT, UPDATE, DELETE
                name: "dat_user",
                sql: sql,
            },
        };
        // console.log('_setLogin', msg); 
        this._socket.emit("META", msg);
    }

    hasMapData(user_id){
        var sql = `SELECT 
                        COUNT(*) AS count 
                    FROM 
                        medba.dat_map 
                    WHERE 
                        user_id = ${user_id}`;
        var msg = {
            cmd: "query", // server端要进行判断的
            data: {
                name: "name", // 这个无所谓怎么写，有就行
                sql: sql,
            },
        };
        this._socket.emit("REPT", msg, (datas) => {
            if(datas.data.length >= 0){
                let count = datas.data[0].count;
                // console.log("has map count ", count);
                if (count !== 0){
                    // PubSub.publish('body.map.none');
                    this.getMapData(user_id);
                } else {
                    // PubSub.publish('body.map.show');
                    this.cteateMapData(user_id);
                }
            }
        });
    }

    getMapData(user_id){
        console.log("getMapData", user_id);
        var sql = `SELECT 
                        map_id,
                        map_data, 
                        map_name, 
                        create_time, 
                        map_uuid, 
                        update_time
                    FROM 
                        medba.dat_map 
                    WHERE 
                        user_id = ${user_id} 
                    ORDER BY 
                        update_time DESC`;
        var msg = {
            cmd: "query", // server端要进行判断的
            data: {
                name: "name", // 这个无所谓怎么写，有就行
                sql: sql,
            },
            };
        this._socket.emit("REPT", msg, (datas) => {
            console.log(datas.data);
            const result = datas.data;
            window.editor_user.maps = [];
            for (let i = 0; i < result.length; i++) {
                const map = result[i];
                // console.log(map);
                window.editor_user.maps.push(map);
            }

            PubSub.publish('body.map.got');
        });        
    }
    
    _getIDByTime(){
        let uuid = "sw" + Date.now().toString(36).slice(-8);
        console.log(uuid);
        return uuid;
    }

    cteateMapData(user_id, map_name = 'map'){
        var sql = `INSERT INTO 
                    medba.dat_map 
                        (map_name, map_data, user_id, update_time, create_time, map_uuid) 
                    VALUES 
                        ('${map_name}', '{ "type": "FeatureCollection", "features": [], "center": { "x": 116.39639, "y": 39.91638 } }', 
                        ${user_id}, NOW(), NOW(), '${this._getIDByTime()}')`;
        var msg = {
            cmd: "update", // server端要进行判断的
            data: {
                op: "INSERT", // INSERT, UPDATE, DELETE
                name: "dat_map",
                sql: sql,
            },
        };
        // console.log("cteateMapData", msg);
        this._socket.emit("META", msg);

        setTimeout(() => {
            const id = user_id;
            this.getMapData(id);
        }, 1000);
    }

    updateMapData(data){
        var sql = `UPDATE medba.dat_map 
                    SET 
                        map_data  = '${data.map_data}',
                        update_time = NOW() 
                    WHERE 
                        user_id = ${data.user_id} AND 
                        map_id = ${data.map_id}`;
        var msg = {
            cmd: "update", // server端要进行判断的
            data: {
                op: "UPDATE", // INSERT, UPDATE, DELETE
                name: "dat_map",
                sql: sql,
            },
        };
        console.log('updateMapData', msg); 
        this._socket.emit("META", msg);

        setTimeout(() => {
            this.getMapData(data.user_id);
        }, 1000);
    }

    updateMapDataDontGet(data){
        var sql = `UPDATE medba.dat_map 
            SET 
                map_data  = '${data.map_data}',
                update_time = NOW() 
            WHERE 
                user_id = ${data.user_id} AND 
                map_id = ${data.map_id}`;
        var msg = {
            cmd: "update", // server端要进行判断的
            data: {
                op: "UPDATE", // INSERT, UPDATE, DELETE
                name: "dat_map",
                sql: sql,
            },
        };
        // console.log('updateMapData', msg); 
        this._socket.emit("META", msg);
        console.log("autosave");
    }

    deleteMapData(map_id){
        var sql = `DELETE FROM medba.dat_map 
                    WHERE  
                        map_id = ${map_id}`;
        var msg = {
            cmd: "update", // server端要进行判断的
            data: {
                op: "DELETE", // INSERT, UPDATE, DELETE
                name: "dat_map",
                sql: sql,
            },
        };
        console.log('deleteMapData', msg); 
        this._socket.emit("META", msg);

        setTimeout(() => {
            this.getMapData(window.editor_user.id);
        }, 1000);
    }
}
export default AccountAuth;