$(document).ready(function() {
    // check all for tables
    $('#selectall').on('click', function() {
        $('.selectOne').prop('checked', this.checked);
        if (this.checked) {
            $('.tableAction').removeClass('btn disabled');
        } else {
            $('.tableAction').addClass('btn disabled');
        }
    });

    $('body').on('change', '.selectOne', function() {
        var check = ($('.selectOne:checked').length == $('.selectOne').length);
        $('#selectall').prop("checked", check);
        if ($('.selectOne:checked').length) {
            $('.tableAction').removeClass('btn disabled');
        } else {
            $('.tableAction').addClass('btn disabled');
        }
    });
});


$('.datepicker').datepicker({
    dateFormat: 'yy/mm/dd'
})

/**
 * For date_from and date to
 * @param date_from selector
 * @param date_to selector
 */
function installDateRangeFields(date_from, date_to) {
    $(date_from).datepicker({
        dateFormat: 'yy/mm/dd',
        onSelect: function(){
            console.clear()
            console.log($(this).datepicker('getDate'))
            console.log($(date_to).datepicker('getDate'))
            $(date_to).datepicker( "option",'minDate', $(this).datepicker('getDate'));
        }
    });

    $(date_to).datepicker({
        dateFormat: 'yy/mm/dd',
        onSelect: function(){
            console.clear()
            console.log($(this).datepicker('getDate'))
            $(date_from).datepicker( "option", 'maxDate', $(this).datepicker('getDate'));
        }
    });

}

/**
 * get inuts and select values in given selector
 * @param string:  element identifier
 * @param string: type ['json', 'serialize']
 * @return string or json object depondes on the type
 */
function dataInDiv (element, type){
    let data={};
    $(element).find('input, select, textarea').each(function(){
        if( $(this).attr('name')){
            data[$(this).attr('name')]=$(this).val();
        }
    });

    if ('string' == type) {
        return ($.param(data));
    } else {
        return (data);

    }
}

/**
 * ajax requests handler
 *
 * object of options contains the url, data to send, headers
 */
const ajax= async (options) => {
    // console.log('options',options)
    try{
      let data=options.data,
      method=options.method?options.method:'post',
      config={
        method:method,
        url:options.url,
        onUploadProgress: function (progressEvent) {

        },
        onDownloadProgress: function (progressEvent) {

        },
      }

      if(options.method=='get'){
        config.params=data
      }else{
        config.data=data
      }
      $('.loading').show();
      // console.log('config',config)
      const response= await axios(config);
      $('.loading').hide();
      if(response.status==200){
        return response.data;
      }

      let message=response.data&&response.data.message?response.data.message: 'internetConnectionProblem'
    //   alert(message)
      return false;
    } catch ({response: {data}}) {

        $('.loading').hide();

        console.log('error ',{data})

        $('.ajaxErrorResponse').html(data.message || 'Request Error').fadeIn(500)
        setTimeout(() => {
            // $('.ajaxErrorResponse').fadeOut(500)
        }, 1000);

        return false;
    }
};

/**
 * Data table handler
 */

 // alert("{{ csrf_token() }}")

/**
 * To set the logic of date_from , date_to range
 */
installDateRangeFields('.date_from', '.date_to')

/**
 *
 * Data table handlers
 */
if('object' == typeof dataTable)
if( dataTable.route){
    /**
     * the next var to empty response table or append new response rows to it
     */
    var removeOld= false;
    var trash= false
    const getData= async (url)=>{
        url= url || dataTable.route
        let data= dataInDiv('.search_filter_form')
        if (trash) {
            data.status= 0
        } else {
            data.status= 1
        }
        const response= await ajax({
            url,
            data,
            method: 'get'
        })

        if (removeOld) {
            $(".response").find("tr:gt(0)").remove();
            // disable it for the next call
            removeOld= false;
        }

        $('.response').append(response)
    }
    getData()


    $('body').on('click', '.search', function(e) {
        e.preventDefault();
        removeOld= true
        getData();
    });

    $('body').on('click', '.showArchive', function(e) {
        e.preventDefault();
        removeOld= true
        trash= true
        $('.statusButns').hide()
        $('.statusButns.status_0').show()
        getData();
    });

    $('body').on('click', '.showActive', function(e) {
        e.preventDefault();
        removeOld= true
        trash= false
        $('.statusButns').hide()
        $('.statusButns.status_1').show()
        getData();
    });


    $('body').on('click', '.pagination a', function(e) {
        e.preventDefault();

        const url = $(this).attr('href');
        removeOld= true
        getData(url);
        // window.history.pushState("", "", url);
    });

    $('body').on('click', '.rowAction', async function(e) {
        e.preventDefault();

        const url = $(this).attr('href');
        let data= {
            // '_token': '{{ csrf_token() }}'
        }

        if($(this).hasClass('force')){
            data={...data, force: true}
        }

        const response=await ajax({
            url,
            data,
            method: $(this).data('method')
        })

        if (response && response.message) {
            $(this).closest('tr').remove()

            removeOld= true
            getData();

            $('.ajaxResponse').html(response.message).fadeIn(500)
            setTimeout(() => {
                $('.ajaxResponse').fadeOut(500)
            }, 1000);
        }

    });


    $('body').on('click', '.tableAction', async function(e) {
        e.preventDefault();
        // let ids = $('.selectOne').filter(item=> this.value);
        let ids=[]
        $('.selectOne:checked').each(function(){
            ids.push($(this).val())
        });

        console.clear()
        console.log(ids)

        if (!ids.length) {
            return
        }

        const url = $(this).attr('href');
        let data= {
            ids
            // '_token': '{{ csrf_token() }}'
        }
        if($(this).hasClass('force')){
            data= {...data, force: true }
        }

        $('#selectall').prop('checked', false);
        $('.custom-control-input:checked ~ .custom-control-label::before').css({
            border: 'none',
            background: 'none',
        });

        // return
        $('.tableAction').addClass('btn disabled');
        const response=await ajax({
            url,
            data,
            method: $(this).data('method')
        })

        if (response && response.message) {
            $('.ajaxResponse').html(response.message).fadeIn(500)
            setTimeout(() => {
                $('.ajaxResponse').fadeOut(500)
            }, 1000);

            removeOld= true
            getData();
        }
    });

}
