// set work days

// gantt.setWorkTime({ day:1, hours:false });

const VERSION_GANTT_EDIT_URL = `${base_url}version-gantt/edit/${ganttId}`;
const VERSION_GANTT_UPDATE_URL = `${base_url}version-gantt/update/${ganttId}`;
const ACTIVITY_SET_BASELINE_URL = `${base_url}activity/set-baseline/${ganttId}`;
const ACTIVITY_SYNCHRONIZE_REPORT_URL = `${base_url}activity/synchronize-report/${ganttId}`;
var toggleTasks = "Collapse";
var isBaselineSet = false;
var daysObj = [
    {
        text: "Sunday",
        value: "0"
    },
    {
        text: "Monday",
        value: "1"
    },
    {
        text: "Tuesday",
        value: "2"
    },
    {
        text: "Wednesday",
        value: "3"
    },
    {
        text: "Thursday",
        value: "4"
    },
    {
        text: "Friday",
        value: "5"
    },
    {
        text: "Saturday",
        value: "6"
    }
];
var days = [0,1,2,3,4,5,6]; // Sunday -> Saturday

var selectDayOffChoices = null;

$(document).ready(function() {
    // init select multiple workdays
    selectDayOffChoices = new Choices('#select_dayoff', {
        removeItemButton: true,
        shouldSort: false
        // maxItemCount: 5,
        // searchResultLimit: 5,
        // renderChoiceLimit: 5
    });

    $('#gantt_setting_btn').on('click', async function() {
        const result = await axiosInstance
            .get(VERSION_GANTT_EDIT_URL, HEADER)
            .then(res => res)
            .catch((error) => error.response);

            // console.log("get version gantt result", result)

        if(result && result.status==200){
            if (result.data && result.data.data) {
                var config_dayoff = null;
                // console.log('result.data.data.config_dayoff', result.data.data.config_dayoff)
                if (result.data.data.config_dayoff !== null) {
                    config_dayoff = result.data.data.config_dayoff;

                    if (config_dayoff && config_dayoff.length > 0) {
                        var config_dayoff_arr = config_dayoff.split(',');
                        for (var i=0; i < config_dayoff_arr.length; i++) {
                            var day = daysObj.find(o => parseInt(o.value) === parseInt(config_dayoff_arr[i]));
                            // $('#select_dayoff option[value='+day.value+']').prop("selected", true);
                            // console.log('day', day);
                            selectDayOffChoices.setChoiceByValue(day.value);
                        }
                    }
                }
            }
        }else{
            // closeDialog('failed upload')
            console.log('failed get version gantt');
            gantt.alert({type: "error", text: "Failed to get settings. Please check your internet connection."});
            // alert('Upload failed');
        }
        $('#modal_gantt_setting').modal('show');
    });

    // $('#gantt_setting_btn').on('click', async function() {
    //     $('#modal_gantt_setting').modal('show');
    //     // $('#')
    // });

    $('#btn_save_setting').on('click', async function() {
        // arr.forEach(function (element, key) {
        //     $('#choices-multiple-remove-button3').append(`<option value="${element.id}">${element.name}</option>`)
        //   });
        // var days = [0,1,2,3,4,5,6]; // Sunday -> Saturday

        // for (var i=0; i < days.length; i++) {
        //     gantt.unsetWorkTime({ day:days[i], hours:false });
        // }
        var holidays = [];
        var dayoff = $('#select_dayoff').val();
        // console.log('dayoff', dayoff);
        // if (dayoff.length < 1) return alert('Please add a day off');

        dayoff = dayoff.map(item => parseInt(item));
        // console.log('dayoff after', dayoff);
        var workdays = _.difference(days, dayoff);
        // console.log('workdays', workdays);

        // getCurrentWorkdays();

        // reset the dayoff first
        for (var i=0; i < days.length; i++) {
            gantt.unsetWorkTime({day: days[i], hours: false});
        }
        // gantt.unsetWorkTime({day: 0, hours: false});
        // gantt.unsetWorkTime({day: 1, hours: false});
        // gantt.unsetWorkTime({day: 2, hours: false});
        // gantt.unsetWorkTime({day: 3, hours: false});
        // gantt.unsetWorkTime({day: 4, hours: false});
        // gantt.unsetWorkTime({day: 5, hours: false});
        // gantt.unsetWorkTime({day: 6, hours: false});

        // gantt.setWorkTime({hours: ["8:00-17:00"]});//global working hours
        // gantt.setWorkTime({day: 2, hours: false});// make Tuesdays day-off

        // if (workdays.length > 0) {
        //     for (var i=0; i < workdays.length; i++) {
        //         gantt.setWorkTime({ day:workdays[i], hours:false });
        //     }
        // }

        // console.log('dayoff.length', dayoff.length);

        if (dayoff.length > 0) {
            for (var i=0; i < dayoff.length; i++) {
                gantt.setWorkTime({ day:dayoff[i], hours:false });
            }
        }
        // else if (dayoff.length < 1) {
        //     // work everyday
        //     for (var i=0; i < days.length; i++) {
        //         gantt.unsetWorkTime({day: days[i], hours: false});
        //     }
        // }

        // saveSettings()
        let payload = {
            "config_dayoff": dayoff.join(',')
        }
        // console.log('payload', payload);
        // console.log('HEADER', HEADER);
        const result = await axiosInstance
            .put(VERSION_GANTT_UPDATE_URL, payload, HEADER)
            .then(res => res)
            .catch((error) => error.response);
            // console.log("update settings result", result)
        if (result && result.status === 200) {
            $('#modal_gantt_setting').modal('hide');
            // gantt.alert("Settings updated");
            gantt.message("Settings updated");
        }
        else {
            gantt.alert({type: "error", text: "Failed to update setting"});
        }

        gantt.render();

    });

    $("#gantt_toggle_task_btn").on('click', function(event) {
		toggleCollapseTasks();
	});

    // $("#gantt_toggle_columns_btn").on('click', function(event) {
    //     toggleColumns();
    // })

    $("#gantt-baseline").on('click', function(event) {
        setBaseline();
    });

    $("#gantt-synchronize").on('click', function(event) {
        setSynchronize();
    });

    initHolidays();
    initGanttSettings();
});

async function initHolidays(){
    let payload = {
        "columns": [
            { "name": "version_gantt_id", "logic_operator": "=", "value": ganttId },
            { "name": "proyek_id", "logic_operator": "=", "value": proyekId }
        ],
        "joins": [],
        "orders": { "columns": ["date"], "ascending": true },
        "paging": { "start": 0, "length": -1 }
    }

    $.ajax({
        data:  JSON.stringify(payload),
        url: `${base_url}holiday/search`,
        type: "POST",
        success: function (result) {
            // console.log("cek data", result.data);
            let dataHolidays = result.data || []
            dataHolidays.map((val, index) => {
                // let day = moment(val.date).format("YYYY-MM-DD");
                var a = moment(val.date);
                var b = moment(a).add(val.duration, 'days');
                for (var m = moment(a); m.isBefore(b); m.add(1, 'days')) {
                    let holiday = new Date(m.format('YYYY-MM-DD'));
                    // console.log("cek holiday", holiday)
                    gantt.setWorkTime({
                        date: holiday,
                        hours: false
                    });
                }
                // let holiday = new Date(day);
                // gantt.setWorkTime({
                //     date: holiday,
                //     hours: false
                // });
            });
            gantt.render();
        },
        error: function (data) {

        }
    });
}

async function initGanttSettings() {
    console.log('initGanttSettings');
    // if zoom is day
    $("#scale3").attr('checked', true);
    // toggleCollapseTasks();

    // init to gantt chart view (holidays)
    const result = await axiosInstance
        .get(VERSION_GANTT_EDIT_URL, HEADER)
        .then(res => res)
        .catch((error) => error.response);

    if (result && result.status==200){
        var config_dayoff = result.data.data.config_dayoff;
        var dayoff = [];
        if(config_dayoff && config_dayoff.length > 0){
            dayoff = config_dayoff.split(',');
        }
        // var dayoff = config_dayoff.split(',');

        // reset the dayoff first
        for (var i=0; i < days.length; i++) {
            gantt.unsetWorkTime({day: days[i], hours: false});
        }

        if (dayoff.length > 0) {
            for (var i=0; i < dayoff.length; i++) {
                gantt.setWorkTime({ day:dayoff[i], hours:false });
            }
        }
    }
}

function expandTask(){
    console.log("check expandTask")
    gantt.eachTask(function(task){
        task.$open = true;
    });
    // updateProperty({task_open:true})
    toggleTasks = "Collapse";
    $("#gantt_toggle_task_btn").prop('title', 'Collapse Activities');
    $("#gantt_toggle_task_btn").children().removeClass('fa-expand-alt');
    $("#gantt_toggle_task_btn").children().addClass('fa-compress-alt');
    gantt.render();
}

function toggleCollapseTasks() {
    // collapse task / activity
    console.log('toggleCollapseTasks');
    gantt.eachTask(function(task){
        task.$open = toggleTasks == "Expand";
    });
    if (toggleTasks == "Expand") {
        updateProperty({task_open:true})
        // console.log('to collapse');
        toggleTasks = "Collapse";
        $("#gantt_toggle_task_btn").prop('title', 'Collapse Activities');
        $("#gantt_toggle_task_btn").children().removeClass('fa-expand-alt');
        $("#gantt_toggle_task_btn").children().addClass('fa-compress-alt'); // change icon to collapse
    } else {
        // console.log('to expand');
        updateProperty({task_open:false})
        toggleTasks = "Expand";
        $("#gantt_toggle_task_btn").prop('title', 'Expand Activities');
        $("#gantt_toggle_task_btn").children().removeClass('fa-compress-alt');
        $("#gantt_toggle_task_btn").children().addClass('fa-expand-alt'); // change icon to expand
    }
    gantt.render();
}


// Function Show / Hide Columns
function getColumnsSelection(node){
    var selectedColumns = node.querySelectorAll(":checked");
    var unselectedColumn = node.querySelectorAll('input[type="checkbox"]:not(:checked)');
    // var allSelected = node.querySelector("#check-all").prop('checked');
    // console.log("unselectedColumn", unselectedColumn)
    var checkedColumns = {};
    selectedColumns.forEach(function(node){
        checkedColumns[node.name] = true;
    });
    unselectedColumn.forEach(function(node){
        checkedColumns[node.name] = false;
    });
    // console.log("checkedColumns", checkedColumns)
    return checkedColumns;
}

function populateColumnsDropdown(node){
    var visibleColumns = {};
    // var preventHide = ['action'];
    gantt.config.columns.forEach(function(col){
        visibleColumns[col.name] = true;
    });

    var lines = [];
    allColumns.forEach(function(col){
        var checked = visibleColumns[col.name] ? "checked" : "";
        // skip action to be pushed
        lines.push(`<label class="${col.name === 'action' ? 'elm-hide2': ''} dropdown-item"><input type="checkbox" name="${col.name}" ${checked}> ${col.label}</label>`);
    });
    node.innerHTML = '<span class="dropdown-title">Show / Hide Columns</span><br>' + lines.join("<br>");
}

function getDropdownNode(){
    return document.querySelector("#gantt_dropdown");
}

gantt.$showDropdown = function(node){
    var position = node.getBoundingClientRect();
    var dropDown = getDropdownNode();
    dropDown.style.top = position.bottom + "px";
    dropDown.style.left = position.left - 150 + "px";
    dropDown.style.display = "block";
    populateColumnsDropdown(dropDown);

    dropDown.onchange = function(){
        var selection = getColumnsSelection(dropDown);
        if(readOnly && parseInt(readOnly)==0){
            updateShowHideColumn(selection)
        }
        gantt.config.columns = createColumnsConfig(selection);
        gantt.render();
    }

    dropDown.keep = true;
    setTimeout(function(){
        dropDown.keep = false;
    })
}

gantt.$hideDropdown = function(){
    var dropDown = getDropdownNode();
    dropDown.style.display = "none";
}

window.addEventListener("click", function(event){
    if(!event.target.closest("#gantt_dropdown") && !getDropdownNode().keep){
        gantt.$hideDropdown();
    }
});

// End Function Show / Hide Columns


// Set Baseline
function setBaseline() {
    var box = gantt.confirm({
        text: "Set Baseline for this gantt chart?",
        ok:"Yes",
        cancel:"No",
        callback: async function(result){
            if(result){
                // gantt.message("Yes!");
                // send to API
                await setBaselineAPI();
            }else{
                // gantt.message("No...");
            }
        }
    });
}

async function setBaselineAPI() {
    const res = await axiosInstance
        .get(ACTIVITY_SET_BASELINE_URL, HEADER)
        .then(res => res)
        .catch((error) => error.response);
    console.log('set baseline res', res);
    if (res && res.status === 200) {
        // $('#modal_gantt_setting').modal('hide');
        // gantt.alert("Settings updated");
        // gantt.message(result.data.message);
        gantt.message("Set baseline success!");
        window.location.reload();
    }
    else {
        gantt.alert({type: "error", text: "Failed to set baseline"});
    }
    gantt.render();
}

function setSynchronize() {
    if (!isBaselineSet) {
        // gantt.alert({
        //     title:"Synchronize to Report",
        //     type:"alert-error",
        //     text:"Please set baseline before continue."
        // });
        gantt.confirm({
            text: "Plase set baseline before continue.",
            ok:"Set Baseline",
            cancel:"Cancel",
            callback: async function(result) {
                if (result) {
                    await setBaselineAPI();
                }
            }
        });
        return false;
    }

    var box = gantt.confirm({
        text: "Synchronize to Report Activity?",
        ok:"Yes",
        cancel:"No",
        callback: async function(result){
            if(result){
                // gantt.message("Yes!");
                // send to API
                await setSynchronizeAPI()
            }else{
                // gantt.message("No...");
            }
        }
    });
}

async function setSynchronizeAPI() {
    const res = await axiosInstance
        .get(ACTIVITY_SYNCHRONIZE_REPORT_URL, HEADER)
        .then(res => res)
        .catch((error) => error.response);

    console.log('synchronize res', res);
    if (res && res.status === 200) {
        // $('#modal_gantt_setting').modal('hide');
        // gantt.alert("Settings updated");
        // gantt.message(result.data.message);
        gantt.message("Synchronize to Report success!");
        window.location.reload();
    }
    else {
        gantt.alert({type: "error", text: "Failed to Synchronize to Report"});
    }
    gantt.render();
}