var i=0;
var indexEdit = -1;
var questions =[];
var answers = [];
var corrects=[];
var url="";
var current = 0;
var EditBack=-1;
var key=0;

$('.pdfopen').on('click',function(){

    //alert('fgrg');
    var url = $(this).data('path');
    //alert(url);
    var c = "/storage/contenu/"+url;
    console.log(c);
    var w=window.open(c, '_blank');
    w.focus();
});

$('#suggestnew').on('click',function(e){
    //i=i+1;
    e.preventDefault();
    if(indexEdit==-1)
    var html = '<div class="uk-flex uk-flex-middle">'+
    '<input class="uk-input"  type="text" placeholder="Réponse.." name="answers['+i+'][]">'+
    '<input class="qcm uk-checkbox uk-margin-left" name="corrects['+i+'][]" type="checkbox">'+
    '</div>';
    else 
    var html = '<div class="uk-flex uk-flex-middle">'+
    '<input class="uk-input"  type="text" placeholder="Réponse.." name="answers['+indexEdit+'][]" >'+
    '<input class="qcm uk-checkbox uk-margin-left" name="corrects['+indexEdit+'][]" type="checkbox">'+
    '</div>';

$('.suggestions').append(html);


});


$('#suggestnewedit').on('click',function(e){
    
    e.preventDefault();
    if(indexEdit==-1){
    if(questions!=null)
        i=questions.length+1;
    else i=0;
    var html = '<div class="uk-flex uk-flex-middle">'+
    '<input class="uk-input"  type="text" placeholder="Réponse.." name="answers['+i+'][]">';
    '<input class="qcm uk-checkbox uk-margin-left" name="corrects['+i+'][]" type="checkbox">'+
    '</div>';
    }else 
    var html = '<div class="uk-flex uk-flex-middle">'+
    '<input class="uk-input"  type="text" placeholder="Réponse.." name="answers['+indexEdit+'][]" >'+
    '<input class="qcm uk-checkbox uk-margin-left" name="corrects['+indexEdit+'][]" type="checkbox">'+
    '</div>';

$('.editsuggestions').append(html);


});


$('#save').on('click',function(e){
    e.preventDefault();
    //var questions = document.getElementsByName("questions[]");
    //var x = document.getElementsByName("answers");
});


$('.editpdf').on('click',function(){
    
    $('#keypdf').val($(this).data('id'));
    $('#titrepdfedit').val($(this).data('titre'));
    
});

$('.edittexte').on('click',function(){
    
    $('#keytext').val($(this).data('id'));
    $('#titreedittext').val($(this).data('titre'));
    $('#content').val($(this).data('content'))
    
});

$('.editvideo').on('click',function(){
    
    key = $(this).data('id');
    url= $(this).data('uri');
    $('#titreeditvideo').val($(this).data('titre'));
    
});

$('.open2').on('click',function(){
    
    key = $(this).data('id');
    url= $(this).data('uri');
    //$('#titreeditvideo').val($(this).data('titre'));
    
});




$('.editqcmtoggle').on('click',function(){
    
    var qcm =$(this).data('id');
    console.log(qcm);
    questions=[];
    questions=qcm;
    key =$(this).data('number');

 console.log(qcm);
    $('#EdittitreQCM').val($(this).data('titre'));
    var html ="";
    if(qcm != null)
    qcm.forEach((element,index) => {
        EditBack=index;
        //alert('index');
        //alert(index);
        i=EditBack;
        html = html+'<div class="uk-margin-small" id="'+EditBack+'">'+
    '<div class="uk-card uk-card-body uk-card-small uk-background-muted uk-border-rounded uk-flex uk-flex-between">'+
        '<div>'+
            '<div class="uk-text-bold quest">'+element.question+'</div>'+
            '<ul class="uk-list uk-list-collapse uk-margin-remove anss">'; 
            element.answers.forEach(e => {
            
                html=html+'<li>'+e+'</li>';
                
            });
            html = html +  
            '</ul>'+
        '</div>'+
        '<div class="delete-item">'+
            '<span class="uk-text-danger" onclick="delItm2('+EditBack+')" data-id="'+EditBack+'"  uk-icon="icon: delete"></span>'+
            '<span class="uk-text-danger" onclick="edtItm2('+EditBack+')" data-id="'+EditBack+'"  uk-icon="icon: edit"></span>'+

        '</div>'+
    '</div>'+
'</div>';
});
$('#editscrolllist').html('');

$('#editscrolllist').append(html);
        
});
    


$('#deletevideo').on('click',function(){


    var client =new Vimeo(
        key1,key2,key3);

        client.request(/*options*/{
            method: 'DELETE',
            path: '/videos/'+url+'?fields=uri'
          }, /*callback*/function (error, body, status_code, headers) {
            if (error) {
              console.log('error');
              console.log(error);
            } else {
              console.log('body');
              console.log(body);
            }
          
            console.log('status code');
            console.log(status_code);
            console.log('headers');
            console.log(headers);
          });

          $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        //e.preventDefault();
        
        $.ajax({
            url:"/admin/section/contenu/supprimer",
            method:'POST',
            data:{
                
                'idsec':$('#idSec').val(),
                
                'id':key

                
            },
        
            success:function(){
                window.location.reload();
            },
        
            error: function(jqXHR, textStatus, errorThrown){
                //window.location="http://localhost:8000/login"    
           }         
        });
        



    

});

$('#uploadvideoedit').on('click',function(){

    var file = $('#videoupload2')[0].files[0];      
    var titre = $('#titreeditvideo').val();
    
    if(titre=="") return;
    if(file==undefined) return ;
    $('#js-progressbar2').css('display','');      
    
        var bar = document.getElementById('js-progressbar2');
        
        var client =new Vimeo(
            key1,key2,key3);

            client.request(/*options*/{
                method: 'DELETE',
                path: '/videos/'+url+'?fields=uri'
              }, /*callback*/function (error, body, status_code, headers) {
                if (error) {
                  console.log('error');
                  console.log(error);
                } else {
                  console.log('body');
                  console.log(body);
                }
              
                console.log('status code');
                console.log(status_code);
                console.log('headers');
                console.log(headers);
              });
    
    
        
        
        client.upload(
            file,
            function (uri) {
            console.log('File upload completed. Your Vimeo URI is:', uri)
            url=uri.replace('/videos/','')
            console.log(url)

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            //e.preventDefault();
            
            $.ajax({
                url:"/admin/section/contenu/modifier",
                method:'POST',
                data:{
                    'type':'video',
                    'titre':titre,
                    'id':$('#idSevideo').val(),
                    'content':url,
                    'key':key

                    
                },
            
                success:function(){},
            
                error: function(jqXHR, textStatus, errorThrown){
                    //window.location="http://localhost:8000/login"    
               }         
            });
            
            
            



            },
            function (bytesUploaded, bytesTotal) {
            var percentage = (bytesUploaded / bytesTotal * 100).toFixed(0);
            //console.log(bytesUploaded, bytesTotal, percentage + '%');
            bar.value =percentage;
            console.log(percentage);
            

        

            },
            function (error) {
            console.log('Failed because: ' + error)
            }
        )
    
    
    
    
});



$('#uploadvideo').on('click',function(){
    //var Vimeo = require('vimeo').Vimeo;
   // alert('frfr');
    var file = $('#videoupload')[0].files[0];      
    var titre = $('#titreVideo').val();
    alert(file);
    alert(titre);
    if(titre=="") return;
    if(file==undefined) return ;
    $('#js-progressbar').css('display','');      
    
        var bar = document.getElementById('js-progressbar');
        var client =new Vimeo(
            key1,key2,key3);
        
        client.upload(
            file,
            function (uri) {
            console.log('File upload completed. Your Vimeo URI is:', uri)
            url=uri.replace('/videos/','')
            console.log(url)

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            //e.preventDefault();
            
            $.ajax({
                url:"/admin/section/contenu/ajouter",
                method:'POST',
                data:{
                    'type':'video',
                    'titre':titre,
                    'id':$('#idSection').val(),
                    'content':url,
                    
                },
            
                success:function(){},
            
                error: function(jqXHR, textStatus, errorThrown){
                    //window.location="http://localhost:8000/login"    
               }         
            });
            
            
            



            },
            function (bytesUploaded, bytesTotal) {
            var percentage = (bytesUploaded / bytesTotal * 100).toFixed(0);
            //console.log(bytesUploaded, bytesTotal, percentage + '%');
            bar.value =percentage;
            console.log(percentage);
            

        

            },
            function (error) {
            console.log('Failed because: ' + error)
            }
        )
        
});

function delItm(d){
    var x = questions[d];
    questions.splice(d,1);
    $('#'+d+'').html('');
    console.log('i am to delee');
    console.log(x);
}


function edtItm(d){
    alert('heree');
    alert(d);
    indexEdit=d;
    var x = questions[d];
    alert(x.answers);
    $('#question').val(x.question);
    var html ='';
    console.log(x);
    
    console.log(x.answers);
    x.answers.forEach((element,index) => {
        alert(index);
        alert(x.corrects[index]);
        html =html+'<div class="uk-flex uk-flex-middle">'+
    '<input class="uk-input"  type="text" placeholder="Réponse.." name="answers['+d+'][]" id='+d+' value="'+element+'">';

    if(x.corrects[indes]=="true")
    html=html+'<input class="qcm uk-checkbox uk-margin-left" name="corrects['+d+'][]" type="checkbox" checked>'+
    '</div>';
    else 
    html=html+'<input class="qcm uk-checkbox uk-margin-left" name="corrects['+d+'][]" type="checkbox">'+
    '</div>';
    

        
    });
$('.suggestions').html('');
$('.suggestions').append(html);




}


function delItm2(d){
    indexEdit=d;
    alert(d);
    var x = questions[d];
    questions.splice(d,1);
console.log(questions);
i=questions.length;
    $('#'+d+'').html('');
    console.log('i am to delee');
    console.log(x);
}


function edtItm2(d){
    alert('heree edt2');
    alert(d);
    alert(questions.length);
    indexEdit=d;
    var x = questions[d];
    console.log('here answers');
       
    alert(x);
    alert(x.answers);
    $('#questionedit').val(x.question);
    var html ='';
    console.log(x);
    
    console.log(x.answers);
    x.answers.forEach((element,index) => {
        alert(index);
        alert(x.corrects[index]==true);
        html =html+'<div class="uk-flex uk-flex-middle">'+
    '<input class="uk-input"  type="text" placeholder="Réponse.." name="answers['+d+'][]" id='+d+' value="'+element+'">';
    if(x.corrects[index]=="true")
    html=html+'<input class="qcm uk-checkbox uk-margin-left" name="corrects['+d+'][]" type="checkbox" checked>'+
    '</div>';
    else
    html=html+'<input class="qcm uk-checkbox uk-margin-left" name="corrects['+d+'][]" type="checkbox">'+
    '</div>';
    

        
    });
$('.editsuggestions').html('');

$('.editsuggestions').append(html);


}

$('#saveqst').on('click',function(e){
    
    if(indexEdit==-1){
    e.preventDefault();
    var x = document.getElementsByName("answers["+i+"][]");
    var ans=[];
    if(x.length>0)
    x.forEach(element => {
        ans.push(element.value);
    });

    var corr=[];
    var corrects = document.getElementsByName("corrects["+i+"][]");
    if(corrects.length>0)
    corrects.forEach(element => {
        corr.push(element.checked);
    });

    var question = $('#question').val();
    var item = {'question':question,'answers':ans,'corrects':corr};
    
    questions.push(item);
    console.log(questions);
    
    var html = '<div class="uk-margin-small" id="'+i+'">'+
    '<div class="uk-card uk-card-body uk-card-small uk-background-muted uk-border-rounded uk-flex uk-flex-between">'+
        '<div>'+
            '<div class="uk-text-bold quest">'+question+'</div>'+
            '<ul class="uk-list uk-list-collapse uk-margin-remove anss">'; 
            x.forEach(element => {
            
                html=html+'<li>'+element.value+'</li>';
                
            });
            html = html +  
            '</ul>'+
        '</div>'+
        '<div class="delete-item">'+
            '<span class="uk-text-danger" onclick="delItm('+i+')" data-id="'+i+'"  uk-icon="icon: delete"></span>'+
            '<span class="uk-text-danger" onclick="edtItm('+i+')" data-id="'+i+'"  uk-icon="icon: edit"></span>'+

        '</div>'+
    '</div>'+
'</div>';
$('#scrolllist').append(html);
i=i+1;
$('.suggestions').html('');

}else {


    alert('editme');
    e.preventDefault();
    var x = document.getElementsByName("answers["+indexEdit+"][]");
    var ans=[];
    if(x.length>0)
    x.forEach(element => {
        ans.push(element.value);
    });
    var corr=[];
    var corrects = document.getElementsByName("corrects["+indexEdit+"][]");
    if(corrects.length>0)
    corrects.forEach(element => {
        corr.push(element.checked);
    });

    var question = $('#question').val();
    var item = {'question':question,'answers':ans,'corrects':corr};
    
    questions.slice(indexEdit,1);
    questions.splice(indexEdit,0,item);
    console.log(questions);


    var html = '<div class="uk-margin-small" id="'+indexEdit+'">'+
    '<div class="uk-card uk-card-body uk-card-small uk-background-muted uk-border-rounded uk-flex uk-flex-between">'+
        '<div>'+
            '<div class="uk-text-bold quest">'+question+'</div>'+
            '<ul class="uk-list uk-list-collapse uk-margin-remove anss">';
    
        
            
            x.forEach(element => {
            
                html=html+'<li>'+element.value+'</li>';
                
            });
            html = html +  
            '</ul>'+
        '</div>'+
        '<div class="delete-item">'+
            '<span class="uk-text-danger" onclick="delItm('+indexEdit+')" data-id="'+i+'"  uk-icon="icon: delete"></span>'+
            '<span class="uk-text-danger" onclick="edtItm('+indexEdit+')" data-id="'+i+'"  uk-icon="icon: edit"></span>'+

        '</div>'+
    '</div>'+
'</div>';
$('#scrolllist #'+indexEdit+'').html('');

$('#scrolllist #'+indexEdit+'').append(html);
indexEdit=-1;   
$('.suggestions').html('');



}

    
    

});


$('#saveqstedit').on('click',function(e){
    if(indexEdit!=-1){
    alert('editme');
    e.preventDefault();
    var x = document.getElementsByName("answers["+indexEdit+"][]");
    var ans=[];
    x.forEach(element => {
        ans.push(element.value);
    });
    var corr=[];
    var corrects = document.getElementsByName("corrects["+indexEdit+"][]");
    corrects.forEach(element => {
        corr.push(element.checked);
    });

    var question = $('#questionedit').val();
    var item = {'question':question,'answers':ans,'corrects':corr};
    
    questions.splice(indexEdit,1,item);
    //questions.splice(indexEdit,0,item);
    console.log('i am after edit');
    console.log(questions);


    var html = '<div class="uk-margin-small" id="'+indexEdit+'">'+
    '<div class="uk-card uk-card-body uk-card-small uk-background-muted uk-border-rounded uk-flex uk-flex-between">'+
        '<div>'+
            '<div class="uk-text-bold quest">'+question+'</div>'+
            '<ul class="uk-list uk-list-collapse uk-margin-remove anss">';
    
        
            
            x.forEach(element => {
            
                html=html+'<li>'+element.value+'</li>';
                
            });
            html = html +  
            '</ul>'+
        '</div>'+
        '<div class="delete-item">'+
            '<span class="uk-text-danger" onclick="delItm2('+indexEdit+')" data-id="'+i+'"  uk-icon="icon: delete"></span>'+
            '<span class="uk-text-danger" onclick="edtItm2('+indexEdit+')" data-id="'+i+'"  uk-icon="icon: edit"></span>'+

        '</div>'+
    '</div>'+
'</div>';
$('#editscrolllist #'+indexEdit+'').html('');

$('#editscrolllist #'+indexEdit+'').append(html);
indexEdit=-1;   
$('.editsuggestions').html('');

}else {
    
    e.preventDefault();
    var x = document.getElementsByName("answers["+i+"][]");
    var ans=[];
    x.forEach(element => {
        ans.push(element.value);
    });
    var corr=[];
    var corrects = document.getElementsByName("corrects["+i+"][]");
    corrects.forEach(element => {
        corr.push(element.checked);
    });

    var question = $('#questionedit').val();
    var item = {'question':question,'answers':ans,'corrects':corr};
    
    if(questions==null) questions=[];
    questions.push(item);
    console.log(questions);
    
    var html = '<div class="uk-margin-small" id="'+i+'">'+
    '<div class="uk-card uk-card-body uk-card-small uk-background-muted uk-border-rounded uk-flex uk-flex-between">'+
        '<div>'+
            '<div class="uk-text-bold quest">'+question+'</div>'+
            '<ul class="uk-list uk-list-collapse uk-margin-remove anss">'; 
            x.forEach(element => {
            
                html=html+'<li>'+element.value+'</li>';
                
            });
            html = html +  
            '</ul>'+
        '</div>'+
        '<div class="delete-item">'+
            '<span class="uk-text-danger" onclick="delItm2('+i+')" data-id="'+i+'"  uk-icon="icon: delete"></span>'+
            '<span class="uk-text-danger" onclick="edtItm2('+i+')" data-id="'+i+'"  uk-icon="icon: edit"></span>'+

        '</div>'+
    '</div>'+
'</div>';
$('#editscrolllist').append(html);
i=questions.length+1;
$('.editsuggestions').html('');


}

});


$('#saveedit').on('click',function(e){
    e.preventDefault();
    alert(key);
    e.preventDefault();
    alert('i am here saveedit');
    console.log(questions);
    if($('#EdittitreQCM').val()=="") return ; 
    
    
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    e.preventDefault();
    
    $.ajax({
        url:"/admin/section/contenu/modifier",
        method:'POST',
        data:{
            'type':'qcm',
            'titre':$('#EdittitreQCM').val(),
            'id':$('#idSe').val(),
            'content':questions,
            'key':key
            
        },
    
        success:function(data){
            window.location.reload();
        },
    
        error: function(jqXHR, textStatus, errorThrown){
            //window.location="http://localhost:8000/login"    
       }         
    });
    
   
});

$('#save').on('click',function(e){
    e.preventDefault();
    
    if($('#titreQCM').val()=="") return ; 
    
    
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    e.preventDefault();
    
    $.ajax({
        url:"/admin/section/contenu/ajouter",
        method:'POST',
        data:{
            'type':'qcm',
            'titre':$('#titreQCM').val(),
            'id':$('#idSec').val(),
            'path':questions,
            
        },
    
        success:function(data){
            window.location.reload();
        },
    
        error: function(jqXHR, textStatus, errorThrown){
            //window.location="http://localhost:8000/login"    
       }         
    });
    
    
});

