var editorTemplate;
var nbOfPeriode;
var nbOfLevel;
var emptyPeriode;

function initScheduleEditor(id, eventType,mode = 'normal')
{
    $.ajax({
        type: 'GET',
        url: '/api/schedule/editor/init/'+eventType+'?api_token='+api_token,
        success: function (template) {
            $("#"+id).html(template);
            for (let pniveau = 1; pniveau <= nbOfLevel; pniveau++) {
                for (let pperiode = 1; pperiode <= nbOfPeriode; pperiode++) {
                    loadCourse(pniveau,pperiode,eventType,mode);
                }
            }
            initAutoComplete("AutoCompleteUser");
            initAutoCompleteOCOM('AutoCompleteOCOM');
        },
        error:  function () {
            showNotification('error','Impossible d\'initialiser l\'éditeur d\'horaire ...','top', 'center')
        }
    });
    $('.datetimepicker').datetimepicker({
        icons: {
            time: "fa fa-clock-o",
            date: "fa fa-calendar",
            up: "fa fa-chevron-up",
            down: "fa fa-chevron-down",
            previous: 'fa fa-chevron-left',
            next: 'fa fa-chevron-right',
            today: 'fa fa-screenshot',
            clear: 'fa fa-trash',
            close: 'fa fa-remove'
        }
    });
    $('.richeditor').trumbowyg({
        lang: 'fr',
        btns: [
            ['viewHTML'],
            ['emoji'],
            ['undo', 'redo'], // Only supported in Blink browsers
            ['strong', 'em', 'del'],
            ['superscript', 'subscript'],
            ['fontfamily'],
            ['fontsize'],
            ['foreColor', 'backColor'],
            ['link'],
            ['insertImage'],
            ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
            ['unorderedList', 'orderedList'],
            ['horizontalRule'],
            ['removeformat'],
            ['fullscreen']
        ]
    });
    $('select').selectpicker();
}

function switchUseWeeklyMsg()
{

    if($('#use_weekly_msg').is(":checked"))
    {
        $('#collmessagedelasemaine').removeClass('d-none');
    }
    else
    {
        $('#collmessagedelasemaine').addClass('d-none');
    }

}

function switchUseSchedule()
{
    if($('#use_schedule').is(":checked"))
    {
        $('#collschedule').removeClass('d-none');
    }
    else
    {
        $('#collschedule').addClass('d-none');
    }
}

function loadCourse(periode,niveau,id = 1,mode = 'normal')
{
    $.ajax({
        type: 'GET',
        url: '/api/schedule/editor/course/'+niveau+'/'+periode+'/'+id+'?api_token='+api_token,
        success: function (course) {
            $("#container-"+niveau+"-"+periode).html(course);
            if (mode == 'editor')
            {
                $('.no-mandatory').removeAttr('required')
            }
        },
        error:  function () {
            showNotification('error','Impossible de charger les cours ...','top', 'center')
        }
    })
}

function addPeriode()
{
    var periodeToAdd = nbOfPeriode+1;
    $.ajax({
        type: 'GET',
        url: '/api/schedule/editor/emptyperiode/'+periodeToAdd+'?api_token='+api_token+'&nblevel='+nbOfLevel,
        success: function (template) {
            $('#row-'+nbOfPeriode).after(template);
            for (let i = 1; i <= nbOfLevel; i++) {
                loadCourse(periodeToAdd,i);
            }
            nbOfPeriode = periodeToAdd;
            initAutoComplete("AutoCompleteUser");
            initAutoCompleteOCOM('AutoCompleteOCOM');
        },
        error:  function () {
            showNotification('error','Impossible d\'initialiser l\'éditeur d\'horaire ...','top', 'center')
        }
    })
}

function removePeriode()
{
    $('#row-'+nbOfPeriode).remove();
    nbOfPeriode--;
}

function removeLevel()
{
    $('#levelHeader-'+nbOfLevel).remove();
    for (let i = 0; i < nbOfPeriode+1; i++) {
        $('#container-'+nbOfLevel+'-'+i).remove();
    }
    nbOfLevel--;
}

function addLevel()
{
    var levelToAdd = nbOfLevel+1;
    var oldnbOfLevel = nbOfLevel;
    nbOfLevel++;
    $.ajax({
        type: 'GET',
        url: '/api/schedule/editor/levelHeader/'+levelToAdd+'?api_token='+api_token,
        success: function (template) {
            $('#levelHeader-'+oldnbOfLevel).after(template)
            for (let i = 1; i <= nbOfPeriode; i++) {
                $('#container-'+oldnbOfLevel+'-'+i).after('<div id="container-'+levelToAdd+'-'+i+'" niveau="'+levelToAdd+'" periode="'+i+'" class="col m-0 border-bottom border-right scheduleEditor-course">@loaderDot</div>');
            }
            for (let i = 1; i <= nbOfPeriode; i++) {
                loadCourse(i,levelToAdd);
            }
        },
        error:  function () {
            showNotification('error','Impossible d\'ajouter une nouvelle entête de niveau ...','top', 'center')
        }
    })
    setTimeout(function () {
        initAutoComplete("AutoCompleteUser");
        initAutoCompleteOCOM('AutoCompleteOCOM');
    },1000)
}

function loadEventType(date)
{
    var selectInput = $('#type');
    var id = selectInput.val();
    $.ajax({
        type: 'GET',
        url: '/api/schedule/editor/template/'+id+'?api_token='+api_token,
        success: function (data) {
            var result = JSON.parse(data);
            editorTemplate = result;
            nbOfLevel = editorTemplate.schedule_model.niveaux.length;
            nbOfPeriode = editorTemplate.schedule_model.periodes.length;
            initScheduleEditor("scheduleEditor",id);
            $.each(result, function (i, val) {
                if(i == "is_mandatory" || i == "use_schedule" || i == "use_weekly_msg")
                {
                    if(val == 1)
                    {
                        $('#'+i).prop( "checked", true );
                    }
                    else
                    {
                        $('#'+i).prop( "checked", false );
                    }
                    switchUseSchedule();
                    switchUseWeeklyMsg();
                }
                else if(i == "begin_time" || i == "end_time")
                {
                    var foo = $('#'+i);
                    var mdate = moment(date+" "+val);
                    foo.data("DateTimePicker").destroy();
                    foo.datetimepicker({
                        icons: {
                            time: "fa fa-clock-o",
                            date: "fa fa-calendar",
                            up: "fa fa-chevron-up",
                            down: "fa fa-chevron-down",
                            previous: 'fa fa-chevron-left',
                            next: 'fa fa-chevron-right',
                            today: 'fa fa-screenshot',
                            clear: 'fa fa-trash',
                            close: 'fa fa-remove'
                        },
                        date: new Date(mdate)
                    });

                }
                else if(i == "weekly_msg_publication_time")
                {
                    var foo = $('#'+i);
                    var mdate = moment(date+" "+result["begin_time"]);
                    mdate.subtract(5, 'days');
                    foo.data("DateTimePicker").destroy();
                    foo.datetimepicker({
                        icons: {
                            time: "fa fa-clock-o",
                            date: "fa fa-calendar",
                            up: "fa fa-chevron-up",
                            down: "fa fa-chevron-down",
                            previous: 'fa fa-chevron-left',
                            next: 'fa fa-chevron-right',
                            today: 'fa fa-screenshot',
                            clear: 'fa fa-trash',
                            close: 'fa fa-remove'
                        },
                        date: new Date(mdate)
                    });

                }
                else if(i == "location" || i == "name")
                {
                    var foo = $('#'+i);
                    foo.val(val);
                }
                else if(i == "admin_desc")
                {
                    var foo = $('#'+i);
                    foo.trumbowyg('html', val);
                }
                else if(i == "calendar_color")
                {
                    var foo = $('#'+i);
                    foo.val(val);
                    pickr.setColor(val);
                }
                else if(i == "calendar_icon")
                {
                    var foo = $('#'+i);
                    foo.val(val);
                    $('#calendar_icon_display').removeAttr('class');
                    $('#calendar_icon_display').addClass(val);
                }
            });
        },
        error:  function () {
            showNotification('error','Impossible de charger le type d\'évenement ...','top', 'center')
        }
    })
}

function updateCourseName(niveau, periode) {
    setTimeout(function(){
        let val = $('#ocom_n'+niveau+'_p'+periode).val();
        if(val != "")
        {
            $.ajax({
                type: 'GET',
                url: '/api/ocom/'+val+'/name?api_token='+api_token,
                success: function (data) {
                    if(data != null && data != "")
                    {
                        $('#name_n'+niveau+'_p'+periode).val(data);
                    }
                },
                error:  function () {
                    showNotification('error','Erreur impossible de charger l\'objectif de rendement ...','top', 'center')
                }
            })
        }
    }, 100);
}

function selectCourseMode(mode, niveau, periode)
{
    if(mode == "course")
    {
        $('#descContainer'+niveau+'-'+periode).addClass('d-none');
        $('#isDoneContainer'+niveau+'-'+periode).removeClass('d-none');
        $('#isDoneContainer'+niveau+'-'+periode).addClass('d-flex');
        $('#OCOMContainer'+niveau+'-'+periode).removeClass('d-none');
        $('#nameContainer'+niveau+'-'+periode).removeClass('d-none');
        $('#modeSwitchC'+niveau+'-'+periode).addClass('active');
        $('#modeSwitchO'+niveau+'-'+periode).removeClass('active');
        $('#use_course_n'+niveau+'_p'+periode).prop("checked", true);
    }
    else
    {
        $('#descContainer'+niveau+'-'+periode).removeClass('d-none');
        $('#isDoneContainer'+niveau+'-'+periode).addClass('d-none');
        $('#isDoneContainer'+niveau+'-'+periode).removeClass('d-flex');
        $('#OCOMContainer'+niveau+'-'+periode).addClass('d-none');
        $('#nameContainer'+niveau+'-'+periode).addClass('d-none');
        $('#modeSwitchC'+niveau+'-'+periode).removeClass('active');
        $('#modeSwitchO'+niveau+'-'+periode).addClass('active');
        $('#use_course_n'+niveau+'_p'+periode).prop("checked", false);
    }
}

function selectCourseModePeriode(mode,periode)
{
    for (let i = 0; i < nbOfLevel; i++) {
        selectCourseMode(mode,i+1,periode);
    }
}

function selectCourseModeNiveau(mode,niveau)
{
    for (let i = 0; i < nbOfPeriode; i++) {
        selectCourseMode(mode,niveau,i+1);
    }
}

function updatePlantext(toggle,id)
{
    if($('#'+toggle).is(":checked"))
    {
        $('#'+id).removeClass('text-warning');
        $('#'+id).addClass('text-success');
        $('#'+id).html('Plan de cours remis')
    }
    else
    {
        $('#'+id).addClass('text-warning');
        $('#'+id).removeClass('text-success');
        $('#'+id).html('Plan de cours non remis')
    }
}
