var auth_basic = "";
function on_file_load() {
    let file = document.getElementById("file_input").files[0];
    document.getElementById("file_input_text").innerHTML = file.name;
}
function auth() {
    const login = document.getElementById("login").value;
    const password = document.getElementById("password").value;
    setCookie("login", login);
    setCookie("password", password);
    auth_basic = btoa(Base64._utf8_encode(login + ":" + password));
}
async function init_paths() {
    var link_path = document.createElement('a');
    var path = await IcecastEchoApi.getStreamPath(auth_basic)
    link_path.href = path;
    var path_text = document.createTextNode(path);
    link_path.appendChild(path_text);
    document.getElementById("base_path").appendChild(link_path);

    var link_stats = document.createElement('a');
    var stats = await IcecastEchoApi.getStatisticsPath(auth_basic);
    link_stats.href = stats;
    var stats_text = document.createTextNode(stats);
    link_stats.appendChild(stats_text);
    document.getElementById("base_status_path").appendChild(link_stats);
}
let rules_table = new RuleTable("rules_table");
let start_time_local_with_path = new DateTimePicker("start_time_local_with_path"); 
let start_time_local_with_file = new DateTimePicker("start_time_local_with_file");
$('.timepicker').timepicker({
    timeFormat: 'HH:mm:ss',
    interval: 1,
    defaultTime: '11',
    dynamic: false,
    dropdown: true,
    scrollbar: true
});
document.getElementById("login_button").onclick = async function() {
    auth();
    rules_table.auth_string = auth_basic;
    await rules_table.update_rules();
};
document.getElementById("create_from_file").onclick = async function() {
    await IcecastEchoApi.create_rule_from_file(start_time_local_with_file.dateTime, document.getElementById("file_input").files[0], auth_basic);
    await rules_table.update_rules();
};
document.getElementById("create_from_path").onclick = async function() {
    await IcecastEchoApi.create_rule(start_time_local_with_path.dateTime, document.getElementById("name"), auth_basic);
    await rules_table.update_rules();
};

document.getElementById("login").value = getCookie("login");
document.getElementById("password").value = getCookie("password");
let now = new Date();
start_time_local_with_path.dateTime = now;
start_time_local_with_file.dateTime = now;
auth();
init_paths();
rules_table.auth_string = auth_basic;
rules_table.update_rules();