import axios from 'axios';
import SockJS from 'sockjs-client';
import * as StompJS from "@stomp/stompjs";
import i18next from "i18next";

class GuardianAPI {
    HOST = (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') ? "http://192.168.0.54" : `${GUARDIAN_HOST}`;
    api = null;

    constructor() {
        //console.log("this.HOST => ",this.HOST);
        this.api = axios.create({
            baseURL: this.HOST + '/api/v3',
            timeout: 1000 * 30,
            maxContentLength: Infinity,
            maxBodyLength: Infinity,
            headers: {}
        });
    }

    getErrMsg = (errCode) => {
        return i18next.t('Error.' + errCode);
    };

    encodeParams = (data, nonNull = false) => {
        return Object
            .keys(data)
            .map(key => {
                    if (!nonNull || data[key] !== null) {
                        return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
                    }
                    return null;
                }
            )
            .filter(value => value !== null)
            .join('&');
    };

    getWebSocket = (query) => {
        // console.log("start API getWebSocket");
        const ws = new SockJS(this.HOST + '/ws/v3/auth/status?' + query);
        return ws;
    };

    getQrWebSocket = (qrId) => {
        // console.log("start API getQrWebSocket");
        const query = this.encodeParams({qrId});
        const ws = new SockJS(this.HOST + '/ws/v3/qr/status?' + query);
        return ws;
    };

    getStompHOST = () => { return this.HOST.replace("http","ws"); }

    getStompWS = (query) => {
        const stomp = new StompJS.Client({
            brokerURL: this.getStompHOST() + '/ws/v3/app/websocket?' + query
            //debug: function (data){ console.log("debug => ", data); }
        })
        stomp.activate();
        return stomp;
    }

    getStompQrWS = (qrId) => {
        const query = this.encodeParams({qrId});
        const stomp = new StompJS.Client({
            brokerURL: this.getStompHOST() + '/ws/v3/app/qr/websocket?' + query
            //debug: function (data){ console.log("debug => ", data); }
        })
        stomp.activate();
        return stomp;
    }




    requestAuth = ( clientKey, userKey, isOtpAuth = false ) => {
        // console.log("start API requestAuth");
        return new Promise((resolve, reject) => {
            this.api.post('/auth', {clientKey, userKey, isOtpAuth}, {withCredentials : true})
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    getAuthResult = (query) => {
        // console.log("start API getAuthResult");
        return new Promise((resolve, reject) => {
            this.api.get('/auth?' + query)
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                });
        });
    };

    deleteAuth = (clientKey, userKey, qrId) => {
        // console.log("start API deleteAuth");
        return new Promise((resolve, reject) => {
            this.api.delete('/auth', {data: {clientKey: clientKey, userKey: userKey, qrId: qrId}})
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    getLoginQrUrl = (clientKey) => {
        // console.log("start API getLoginQrUrl");
        return new Promise((resolve, reject) => {
            const query = this.encodeParams({clientKey});
            this.api.get('/qr/generate?' + query)
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                })
        })
    }

    postTotpUserVerify = (clientKey, userKey, otpCode) => {
        // console.log("start API postTotpUserVerify");
        return new Promise((resolve, reject) => {
            this.api.post('/totp/user/verify', {clientKey, userKey, otpCode})
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                })
        })
    };

    getOtpVerify = (clientKey, otpCode) => {
        // console.log("start API getOtpVerify");
        return new Promise((resolve, reject) => {
            this.api.get(`/otp/verify?${this.encodeParams({clientKey, otpCode})}`)
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                })
        })
    };

    postOtpUserVerify = (clientKey, userKey, otpCode) => {
        // console.log("start API postOtpUserVerify");
        return new Promise((resolve, reject) => {
            this.api.post('/otp/user/verify', {clientKey, userKey, otpCode})
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                })
        })
    };
}

export default new GuardianAPI();
