/**
 * This file will depend on dialog.js (soft dependency). Some functions here will make calls to resources in dialog.js
 */

var reset = function(){
    dialog.open('Healthcare/IO::Parser', 'Are you sure you would like to delete all data parsed? Click Ok to confirm',confirmed.reset)
    
}
var update= function(){
    dialog.open('Healthcare/IO::Parser','Update will change parsing configuration. Would you like to continue ?',confirmed.update)
}
var run = function(){
    dialog.open('Healthcare/IO::Parser','Preparing parser, confirm to continue',confirmed.run)
}
var _queue = {socket:null}
var confirmed = {}
confirmed.run = function(){
    dialog.status.busy()
    dialog.status.wait()
    $('.dialog .message .text').html('Initiating Parsing ...')
    setTimeout(function(){
        var http = HttpClient.instance()
        http.post(sessionStorage.io_context+'/io/run',function(x){
        //    dialog.handler = setInterval(function(){monitor.data()},750)
        monitor.data()
        //dialog.close()
    
        })
    
    },1000)
}
confirmed.reset = function(){
    var uri = sessionStorage.io_context+'/reset'
    var http= HttpClient.instance()
    dialog.status.busy()
    dialog.status.wait()
    http.post(uri,function(x){
       setTimeout(function(){
        if (x.status == 200 && x.responseText == "1"){
            dialog.status.success()
            $('.dialog .message .text').html('Reset Healthcare/IO::Parser was successful!<br><div align="center">Dialog will be closing</div>')
            dialog.close()
        }else{
            dialog.status.fail()
            
            
        }

       },2000)
    })
}

confirmed.update = function(){
    var uri = sessionStorage.io_context+'/update'
    var email  = $('#email').val()
    //
    //-- validate the email
    if (email.match(/^([^\s]+)@([^\s@]+)\.(org|com|edu|io)$/i)){
        dialog.status.wait()
        dialog.status.busy()
        var http = HttpClient.instance()
        http.setData({"email":email},"application/son")
        setTimeout(function(){
            http.post(uri,function(x){
                if(x.status == 200 && x.responseText == "1"){
                    dialog.status.success()
                }else{
                    
                    dialog.status.fail()
                    $('.dialog .message .text').html('Error code '+x.status)
                    dialog.bind()
                    dialog.status.confirm()
                    $('.dialog .title-bar .title').html("Error found")
            
                }
            })
    
        },1000)
    }else{
        dialog.status.fail()
        dialog.bind()
        $('.dialog .title-bar .title').text("Error found")
        $('.dialog .message .text').html('Invvalid Email entered')
        dialog.status.confirm()
    }
    
}

/**
 * This namespace is designed to export data to either the cloud or to a database
 */
var publish={set:{}}
publish.post = function(){
    
    if($('.jxmodal').length > 0){
        jx.modal.close()
    }
    dialog.open('Export/ETL','Please wait')
    dialog.status.busy()

    var http = HttpClient.instance()
    http.setData(JSON.parse(sessionStorage.export),"application/json")
    http.post(sessionStorage.io_context+'/export',function(x){
        if (x.status != 200){
            setTimeout(function(){
                $('.dialog .message .text').html('An error occurred with code '+x.status)
                dialog.status.fail()
                dialog.status.wait()
    
            },1500)
            
        }
        //
        // @TODO: Have progress be monitored for this bad boy i.e open the connection to socket and read in ...
        //
    })

}
publish.set.file = function(){
    var file = $('#file')[0].files[0]
    $('.file .name').html(file.name)
    var button = $('.cloud input').prop('disabled',true)
    var div = $('.cloud .file .fa-file-upload')[0]
    $(div).empty()
    $(div).addClass('fas fa-cog fa-spin')
    var reader = new FileReader()
    reader.readAsText(file)
    
    
    reader.onload = function(){
        _args = {"type":$('.cloud .id').html().trim(),"content":reader.result}
        // _args = JSON.stringify(_args)
        if (_args.content.match(/^\{.+/i) == null){
            content = _args.content.split('\n')[1].split(',')
            _args.content = {'bucket':'healthcareio','access_key':content[0].trim(),'secret_key':content[1].trim()}
        }
        sessionStorage.export = JSON.stringify(_args)
    }
    
    reader.onloadend = function(){
        setTimeout(function(){
            var div = $('.cloud .file .fa-cog')[0]
            $(div).empty()
            $(div).addClass('fas fa-check')
            $(div).removeClass('fa-spin')
            // jx.modal.close()
            
            //setTimeout(jx.modal.close,1500)
            publish.post()
        },2000)    
    }
}
publish.database = {}

publish.database.init = function(id){
    //
    // we are expecting id in {mongo,couch,postgresql,mysql,sqlite}
    // @TODO: Account for cloud service brokers like dropbox, box, one-drive and google-drive
    sessionStorage.export = "{}"
    p = {'id':id}
    if (id.match(/(mongodb|postgresql|mysql|sqlite|couchdb)/i)){
        var hide_id = '.store .cloud'
        var show_id = '.store .database'
    }else{
        //
        // @TODO: generate an error message
        var show_id = '.store .cloud'
        var hide_id = '.store .database'

    }
    var http = HttpClient.instance()
    http.get(sessionStorage.io_context+'/export',function(x){
        var html = x.responseText
        jx.modal.show({'html':html,'id':'dialog'})
        $(hide_id).hide(function(){
            $(show_id).show()
        })

        $('.store .id').text(id)
    })

}