class Downloader{
    constructor(){
        this._speed=0;
        this._oldTransferred=-1;
        this._totalTransferred=-1;
        this._oldPercentage=-1;
        this._totalSize=0;
        let ipworks = require("ipworks");

        if(!ipworks) {
            console.error("Cannot find ipworks.");
            return 1;
        }
        this._http = new ipworks.http();
        let  key='31504A42534131535542524131535542414E4742333132370000000000000000000000000000000031335442474D5452000058574E355234434A304A34440000';
        this._http.setRuntimeLicense(key);

        this._intervalID=0
    }
    download(url,filename){
        this._intervalID=setInterval(()=>{
                //console.log("tick tack")
                if(this._oldTransferred!=this._totalTransferred){
                    this._speed=(this._totalTransferred-this._oldTransferred)*10;
                    this._oldTransferred=this._totalTransferred
                }
            },100
        );
        const prettyBytes = require('pretty-bytes');

        this._http.on('Header',(e)=>{
            console.log(e.field,e.value);
            if(e.field=='Content-Length'){
                this._totalSize=e.value*1
            }
        });
        this._http.on("Transfer", (e)=>{
            // console.log(e.text.toString());
            this._totalTransferred=e.bytesTransferred;
            if(this._oldPercentage!=e.percentDone){
                this._oldPercentage=e.percentDone;
                console.log(prettyBytes(e.bytesTransferred) + '/' + prettyBytes(this._totalSize),e.percentDone + '%',prettyBytes(this._speed))
            }
            if(e.bytesTransferred==this._totalSize && this._totalSize>0){
                clearInterval(this._intervalID)
            }

        });
        this._http.on("EndTransfer", (e) => {
            console.log("Transfer finished.");
        });

        this._http.on("SSLServerAuthentication", (e) => {
            e.accept = true;
        });

        this._http.setFollowRedirects(1);
        this._http.setLocalFile(filename);
        this._http.get(url, (err) => {
            if(err) {
                console.log(err);
                process.exit();
            }
            console.log("This is from the callback function.");
        });

    }
}

module.exports = Downloader;