interface AuthInterface {
    endpoint:string;
    key:string;
    socket : WebSocket;
    isInitialized:boolean;
    shouldPing:boolean;
    cPing : any;
}
interface detailsHandlerInterface {
    (details: object);
}
class Authentication implements AuthInterface{
    endpoint : string;
    key: string;
    isInitialized:boolean =false;
    shouldPing:boolean;
    socket : WebSocket;
    cPing : any;
    constructor(API_KEY : string){
        this.endpoint="secure-stream-87726.herokuapp.com";
        this.key=API_KEY;
        this.socket=new WebSocket(`wss://${this.endpoint}/qr`);
        this.init=this.init.bind(this);
        this.getQr=this.getQr.bind(this);
        this.destroy=this.destroy.bind(this);
        this.continousPing=this.continousPing.bind(this);
    }
    continousPing(){
        this.cPing= setInterval(()=>{
            this.socket.send("ping")
        },40000)
    }
    init(detailsHandler : detailsHandlerInterface , ping : boolean = false){
        this.isInitialized = true;
        this.shouldPing=ping;
        this.onRecieveUserDetails=this.onRecieveUserDetails.bind(this,detailsHandler);
    }
    destroy() {
        clearInterval(this.cPing);
        this.socket.close();
    }
    getQr(){
        let self=this;
        if (!self.isInitialized){
            throw "The module is not initialized; call init(...) before getQr()";
        }
        return new Promise(function (resolve, reject) {
            self.socket.onopen = function () {
                self.socket.send(JSON.stringify({
                    "project_name": "Frontend-test",
                    "api_key": self.key,
                    "domain_name": "localhost"
                }));
                if(self.shouldPing)
                    self.continousPing();
                self.socket.onmessage = function (event) {
                    let data = JSON.parse(event.data);
                    if (data.ImageQR !== undefined) {
                        resolve(data.ImageQR);
                    }
                    else if (data.message === "success"){
                        self.onRecieveUserDetails(data);
                    }
                };
            };
        });
    }
    onRecieveUserDetails(userDetailsHandler : detailsHandlerInterface,data?){
        let self= this;
        userDetailsHandler(data.details);
        self.destroy();
    }
}
declare var Auth;
Auth=Authentication;
export default Authentication;