/*
    init(info_div)
    info_div - область div в которой отображается информация загрузки
    Содержит событие(сигнал) 'uploaded', информирующий о завершении загрузки

    upload(file_name)
    file_name - ссылка на файл(blob), TODO: сделать загрузку по имени файла
*/

(function(exports) {
    let query_lines = []
    let error_indexes = []
    let ignored_indexes = []
    let upload_indexes = []
    let upload_info

exports.init = function(info_div)
{
    upload_info = info_div
    query_lines = []
    error_indexes = []
    ignored_indexes = []
    upload_indexes = []

    let status = $('<div id="status">')
    let progress = $('<div id="progress">')
    let ignored = $('<div id="info">')

    info_div.html('')
    info_div.append(status)
    info_div.append(progress)
    info_div.append(ignored)
}

//console.log(file_list)        
exports.upload = function(file_name)
{
    let reader = new FileReader()
    try {
        //let file = new File([""], file_name);
        //reader.readAsText(file)
        reader.readAsText(file_name)
    } catch(error) {
        alert(`Ошибка загрузки файла: ${file_name} ${error}`)
        console.log(error)
        return false
    }

    reader.onload = function() {
        //console.log(reader.result)
        const eds_script = utils.load_script('eds.js')
        Promise.all([
            eds_script
        ])
        .then(() => eds.parse(reader.result))
        .then(eds_file_object => form_query(eds_file_object))
    }

    reader.onerror = function() {
        alert(`Ошибка загрузки файла: ${reader.error}`)
        console.log(reader.error)
    }
}

function form_query(eds_file_object)
{
    let query_item_number = 0
    let query_line = ''       
    let part_number = 0

    $.each(eds_file_object, function (key, item)
    {
        if (!key.includes('sub'))
        {
            return true //continue
        }

        let index = key.replace('sub', '_')
        if (item.AccessType == null)
        {
            return true //continue
        }

        if (item.AccessType.includes('w'))
        {
            if (item.DefaultValue == '' || item.DefaultValue == null)
            {
                ignored_indexes.push(index)
                return true  //continue
            }

            if (query_item_number > 0) { query_line += "&" }
            query_line += utils.get_set_od_data_query_unit(index, item.DefaultValue)
            query_item_number++

            //console.log(query_item_number)
            //if (query_item_number >= REQUEST_PART_SIZE)
            {
                query_lines[part_number] = query_line

                query_line = ''
                part_number++
                query_item_number = 0
            }
        }
        
        //console.log(query_line)
    })
    //console.log(query_lines)
    request_parts(0)
}

function show_indexes(text, indexes)
{
    if (indexes.length > 0)
    {              
        for (let i=0; i<indexes.length; i++)
        {
            text += `<br>${indexes[i]}`
        }

        $('#info').append(`<br>${text}`)
    }
}

function request_parts(current_number)
{
    let query = '/set_od_data.form?' + query_lines[current_number]
    //console.log(query)
    return fetch(query)
    .catch(function(error) {
        alert(`Request failed ${query} ${error.message}` , error)
    })   
    .then(response => response.text())
    .then(text => 
    {
        //console.log(text)
        if ((text.search( />>>ERROR<<</i ) != -1) || (text.search( /!!!ERROR!!!/i ) != -1)  || (text.search( /Error/i ) != -1))
        {
            error_indexes.push(query_lines[current_number])
        }
        else
        {
            upload_indexes.push(query_lines[current_number])
        }
        //console.log(response.statusText)
        current_number++
        utils.get_progress_bar("#progress", current_number, query_lines.length)

        if (current_number < query_lines.length)
        {
            request_parts(current_number)
        }
        else
        {
            $("#status").html(l100n.localize_string('Download Dump Comlite'))
            
            $("#info").append(`<br>${l100n.localize_string("upload_count")}: ${upload_indexes.length}`)
            $("#info").append(`<br>${l100n.localize_string("ignored_count")}: ${ignored_indexes.length}`)
            $("#info").append(`<br>${l100n.localize_string("error_count")}: ${error_indexes.length}`)
            $("#info").append('<br>')
            
            show_indexes(l100n.localize_string('indexes_ignored'), ignored_indexes)
            show_indexes(l100n.localize_string('error_indexes'), error_indexes)
            show_indexes(l100n.localize_string('upload_indexes'), upload_indexes)

            upload_info.trigger('uploaded')
        }
    })
    .catch(function(error) {
        //console.log(query)
        alert(`Request failed ${query} ${error.message}` , error)
    })
}

})(this.upload_dump = {})