var clientUUID = '';
var advancedDisplayed = false;
var json = {};
var jsonIndex = 0;
var host = window.location.protocol + "//" + window.location.hostname + "/mock";

const C_UUID = 'mock-uuid';
const C_ADV = 'advanced-mode';

const color_red = "#ff8f8f";
const color_grey = "#6b6b6b";

const setModified = function(){
    setDataModified();
}

const getUpdate = function(){
    updateData();
}
const dataRefresh = function(){
    getData();
}

/*
    Listeners segment
*/

$(document).on('change', '.data-field', setModified);

$('#btn-save').click( 
    () => {
        disableSaveButton();
    }
    );
    
$('#btn-newRow').click(
    ()=> {
        newRowInput();
        setDataModified();
    }   
    );

/*
    Functions segment
*/

function disableSaveButton(){
    $('#btn-save').removeClass('active');
    $('#btn-save').off();
}

function createLink(uuid){
    var link =  host + '/api/mock/r/'+uuid;
    return link;
}


function onLoad(){
    loadCookies();
    getData();
}

function getData(){
    $.getJSON(host + '/api/mock/'+clientUUID, function(data) {
        json = data;
        loadFetchedMessage();
        initializeUUID();
    });
}

function loadCookies(){
    clientUUID = getCookie(C_UUID);
    advancedDisplayed = getCookie(C_ADV) == 'true';
}

function setCookie(){
    document.cookie = C_UUID + '=' +clientUUID;
    document.cookie = C_ADV + '=' + advancedVisibility;
}

function initializeUUID(){
    if(clientUUID == null || clientUUID == undefined || clientUUID == ''){
        clientUUID = json.clientUUID;
        setCookie();
    }
}

function httpStatusInvalid(){
    value = $('#httpStatus').val();
    return value == '';
}

function setDataModified(){
    if(httpStatusInvalid()){
        $('#btn-save').removeClass('active');
        $('#btn-save').off();
        document.getElementById("httpStatus").style.backgroundColor = color_red;
        return;
    }
        $('#btn-save').addClass('active');
        $('#btn-save').click(getUpdate);
        document.getElementById("httpStatus").style.backgroundColor = null;
}

function getCookie(cname) {
    var name = cname + '=';
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}

function updateData(){
    var updatedJson = createRequestBody();
    const dataSaved = function () {
        loadFetchedMessage();
        savedModalDisplay();
    }
    $.ajax({
        url: host + '/api/mock',
        type: 'PUT',
        data: JSON.stringify(updatedJson, null, 2),
        contentType: "application/json",
    }).done(dataSaved);
    disableSaveButton();
}

function loadFetchedMessage(){
    fillStaticFields(
        json.clientUUID,
        json.contentType,
        json.messageBody,
        json.httpStatus);
    fillHeaderTable(json.httpHeaders);
    initializeHistory();
    refreshHeaderTable(document.innerHTML);
}

function fillStaticFields(uuid, contentType, body, httpStatus){
    let link = createLink(uuid);
    let linkHtml = '<a class="hyperlink" target="_blank" href="'+link+'">'+link+'</a>';
    $('#messageLink').html(linkHtml);
    $('#httpStatus').val(httpStatus);
    $('#typeSelector').val(contentType);
    $('#bodyEditor').val(body);
}

function fillHeaderTable(headers){
    var innerHTML = buildHeaderMapHtml(headers);
    refreshHeaderTable(innerHTML);
}

function refreshHeaderTable(html){
    $('#headerMapTable').html(html);
    $('.btn-hashmap').click(function(){
        setDataModified();
        $(this).closest('tr').remove();
    })
}

function buildHeaderMapHtml(headers){
    var innerHTML = '';
    for(var key in headers){
        innerHTML += buildRowHtml(key, headers[key]);
    }
    return innerHTML;
}

function addRow(key, value){
    var headerMap = $('#headerMapTable');
    var headersMapHtml = headerMap.html();
    headersMapHtml += buildRowHtml(key, value);
    refreshHeaderTable(headersMapHtml);
}

function newRowInput(){
    const hName = $('#headerKeyInput');
    const hValue = $('#headerValueInput');
    if(checkIfInputValid(hName.val()) && checkIfInputValid(hValue.val())){
        addRow(hName.val(), hValue.val());
        hName.val(null);
        hValue.val(null);
    }
}

function checkIfInputValid(input){
    return !(input == '' || input == null || input == undefined);
}

function checkIfHeaderEssential(key){

    if( key == "Connection" || key == "Keep-Alive" || key == "Date" ){
        return true; 
    }
    return false;

}

function buildRowHtml(key, value){

    if(checkIfHeaderEssential(key)){
        return '' + 
        '<tr>' +
            '<td><input class="key data-field" value="' + key + '" readonly></td>' +
            '<td><input class="data-field" value="' + value + '"></td>' +
        '</tr>';
    } 
    return '' + 
    '<tr>' +
        '<td><input class="key data-field" value="' + key + '"></td>' +
        '<td><input class="data-field" value="' + value + '"></td>' +
        '<td><button class="modification-button btn-hashmap"><i class="icon-cancel"></i></button></td>' +
    '</tr>';
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function createRequestBody(){
    var newJson =
        {
            clientUUID: json.clientUUID,
            contentType: $('#typeSelector').val(),
            messageBody: $('#bodyEditor').val(),
            httpStatus: $('#httpStatus').val(),
            httpHeaders: {},
        };
    newJson['httpHeaders'] = convertTableToJson();
    
    json = newJson;
    return newJson;
}


function convertTableToJson(){
    const rows = $('#headerMapTable').children();
    
    var obj = {};
    var key;
    for(let i=0; i<rows.length; i++){
        key = rows.eq(i).children().eq(0).children().eq(0).val();
        obj[key] = rows.eq(i).children().eq(1).children().eq(0).val();
    }
    return obj;
}
