$(document).ready(function () {
    SelectHospital();
    var redirect = 0;
});
var totdayCount = 0;
function SelectHospital() {
    var HospitalData = {
        Dml_Indicator: "HS",
        doctor_id: $('#HiddenDoctorID').val()
    }
    
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HospitalData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
                
            }
            else {
                var data = JSON.parse(data);
                var default_opt = '<option value="0">--Select--</option>';
                var SelHospital = '';
                $('#SelHospital').empty();
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        SelHospital = SelHospital + '<option value="' + data[i].hospital_id + '">' + data[i].hospital_name + '</option>';
                        
                    }
                    $('#SelHospital').append(default_opt+SelHospital);
                }



            }
        }

    });


}
function timeconvert(time) {
    var time = time;
    var hours = Number(time.match(/^(\d+)/)[1]);
    var minutes = Number(time.match(/:(\d+)/)[1]);
    var AMPM = time.match(/\s(.*)$/)[1];
    if (AMPM == "PM" && hours < 12) hours = hours + 12;
    if (AMPM == "AM" && hours == 12) hours = hours - 12;
    var sHours = hours.toString();
    var sMinutes = minutes.toString();
    if (hours < 10) sHours = "0" + sHours;
    if (minutes < 10) sMinutes = "0" + sMinutes;
    time = (sHours + ":" + sMinutes);
    return time;
}





// Convert a time in hh:mm format to minutes
function timeToMins(time) {
    var b = time.split(':');
    return b[0]*60 + +b[1];
}

// Convert minutes to a time in format hh:mm
// Returned value is in range 00  to 24 hrs
function timeFromMins(mins) {
    function z(n){return (n<10? '0':'') + n;}
    var h = (mins/60 |0) % 24;
    var m = mins % 60;
    return z(h) + ':' + z(m);
}

// Add two times in hh:mm format
function addTimes(t0, t1) {
    return timeFromMins(timeToMins(t0) + timeToMins(t1));
}

function converthourstoseconds(hms) {
    var hms = hms;   // your input string
    var a = hms.split(':'); // split it at the colons

    // minutes are worth 60 seconds. Hours are worth 60 minutes.
    var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
    //console.log('sec----' + seconds);
    hms = seconds;
     return hms;
}

$("#BtnSubmit").click(function () {
    
    if ($.trim($('#SelHospital :selected').val()) == "" || $('#SelHospital :selected').val() == "0") {
        $('#PSelHospital').show();
        $('#PSelHospital').fadeOut(8000);
        $('#PSelHospital').html('Select Hospital');
        $('#SelHospital').focus();
        $('#SelHospital :selected').val('0');
        return false;
    }
    
    if ($.trim($('#FDate').val()) == "") {
        $('#PFDate').show();
        $('#PFDate').fadeOut(8000);
        $('#PFDate').html('Select From Date');
        $('#FDate').focus();
        $('#FDate').val('');
        return false;
    }

    if ($.trim($('#EDate').val()) == "") {
        $('#PEDate').show();
        $('#PEDate').fadeOut(8000);
        $('#PEDate').html('Select End Date');
        $('#EDate').focus();
        $('#EDate').val('');
        return false;
    }
    
    //if ($.trim($('#SelDay').val()) == "" || $('#SelDay :selected').val() == "0") {
    //    $('#PSelDay').show();
    //    $('#PSelDay').fadeOut(8000);
    //    $('#PSelDay').html('Select Days');
    //    $('#SelDay').focus();
    //    $('#SelDay :selected').val('0');
    //    return false;
    //}

    if ($.trim($('#SelDay').val()) == "" ) {
        $('#PSelDay').show();
        $('#PSelDay').fadeOut(8000);
        $('#PSelDay').html('Select Days');
        $('#SelDay').focus();
        $('#SelDay :selected').val('0');
        return false;
    }


    if ($.trim($('#FTime').val()) == "") {
        $('#PFTime').show();
        $('#PFTime').fadeOut(8000);
        $('#PFTime').html('Enter From Time');
        $('#FTime').focus();
        $('#FTime').val('');
        return false;
    }

    if ($.trim($('#ETime').val()) == "") {
        $('#PETime').show();
        $('#PETime').fadeOut(8000);
        $('#PETime').html('Enter To Time');
        $('#ETime').focus();
        $('#ETime').val('');
        return false;
    }

    if ($.trim($('#txtPatientTime').val()) == "" || $('#txtPatientTime').val() == "00") {
        $('#PtxtPatientTime').show();
        $('#PtxtPatientTime').fadeOut(8000);
        $('#PtxtPatientTime').html('Enter Per patient handling time');
        $('#txtPatientTime').focus();
        $('#txtPatientTime').val('00');
        return false;
    }
    var from_time = $('#FTime').val();
    from_time = timeconvert(from_time);
    var to_time = $('#ETime').val();
    to_time = timeconvert(to_time);
    console.log(from_time + '-----------------' + to_time);
    if (from_time >= to_time) {
            $('#PETime').show();
            $('#PETime').fadeOut(8000);
            $('#PETime').html('Enter valid To Time');
            $('#ETime').focus();
            $('#ETime').val('');
            return false;
    }
    //$(':input[type="submit"]').prop('disabled', true);
     //$('#BtnSubmit').attr('disable',true);
    $('#BtnSubmit').hide();
    $('.shade_main').css('display', 'block');
    //if (($.trim($('#SelHospital :selected').val()) != "" || $('#SelHospital :selected').val() != "0") && ($.trim($('#FDate').val()) != "") && ($.trim($('#EDate').val()) != "") && ($.trim($('#SelDay').val()) != "" || $('#SelDay').val() != "0") && ($.trim($('#FTime').val()) != "") && ($.trim($('#ETime').val()) != "") && ($.trim($('#txtPatientTime').val()) != "" || $('#txtPatientTime').val() != "00")) {
        var Fdate, Edate, formated_Fdate, formated_Edate;
        var FDate = $('#FDate').val();
        Fdate = FDate.split('/');
        formated_Fdate = Fdate[1] + '/' + Fdate[0] + '/' + Fdate[2];
        Fdate = new Date(formated_Fdate);
        // console.log(Fdate);

        var EDate = $('#EDate').val();
        Edate = EDate.split('/');
        formated_Edate = Edate[1] + '/' + Edate[0] + '/' + Edate[2];
        Edate = new Date(formated_Edate);
        // console.log(Edate);

       // var tot = (Edate.getDate() - Fdate.getDate());
        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
        //var firstDate = new Date(2008, 01, 12);
        //var secondDate = new Date(2008, 01, 22);

        var diffDays = Math.round(Math.abs((Fdate.getTime() - Edate.getTime()) / (oneDay)));
        //alert(diffDays);
        //return false;
        // var days = (Edate - Fdate) / 1000 / 60 / 60 / 24;
        // console.log('tot----'+tot);
        // console.log(days);
        var SelDay = $('#SelDay').val();
        //  console.log(SelDay);
        //  console.log(Edate.getDay());
        var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        var check = new Date(Fdate);
       
        
        for (var i = 0; i <= diffDays; i++) {
            
            //console.log('Fdate.getDate()----' + Fdate.getDate() + '-----i-------' + i);
            // console.log(Fdate.getDate() + 1);
            // console.log('i------------' + i);
            //console.log(check);
            if (i > 0) {

                check = new Date(Fdate.setDate(Fdate.getDate() + 1));
            }
            for (var j = 0; j <= diffDays ; j++) {
                
                if (check.getDay() == SelDay[j]) {
                    // console.log(check);
                    var date = check.getDate();
                    var month = check.getMonth() + 1;
                    var year = check.getFullYear();
                    // console.log(month);

                    if (date < 10) {
                        date = '0' + date;
                    }
                    if (month < 10) {
                        month = '0' + month;
                    }
                    console.log(month);
                    var convertdate = year + '-' + month + '-' + date;
                    totdayCount++;
                    
                    insert(convertdate, from_time, to_time);
                    // console.log(convertdate);
                }
                //console.log('j------------' + j);

            }

            //console.log(check);
        }
    // }
       // redirect();
});
var ajaxroundcount = 0;
function redirectfun() {
    window.location.href = '/CalendarConfigurationList/';
}
function insert(date, from_time, to_time) {
    var perpatienttime = $('#txtPatientTime').val();
    console.log(perpatienttime);
    var HospitalData = {
        Dml_Indicator: "I",
        doctor_id: $('#HiddenDoctorID').val(),
        hospital_id: $('#SelHospital').val(),
        schedule_date: date,
        from_time: date + " " + from_time,
        to_time: date + " " + to_time,
        per_patient_time: perpatienttime,
        schedule_status:1
    }
    //console.log(HospitalData);
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/CalendarConfiguration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HospitalData),
        success: function (data) {
            slotInsert(data);
            ajaxroundcount++;
            //var a= StringMsg
            
           // $.when(slotInsert(data)).then(redirect());
        }


    });
   
}

    function slotInsert(data) {
    
    var data1 = JSON.parse(data);
    var doctorScheduleId;
    var Rschedule_date;
    for (var i = 0; i < data1.length; i++) {
        doctorScheduleId = data1[i].StringMsg;
        Rschedule_date = data1[i].Rschedule_date;
        //alert(doctorScheduleId);
    }
    var from_time = $('#FTime').val();
    from_time = timeconvert(from_time);
    var to_time = $('#ETime').val();
    to_time = timeconvert(to_time);
    var SlotTime = $('#txtPatientTime').val();
    var SlotConvertTime;
    if (SlotTime == "60") {
        SlotConvertTime = converthourstoseconds('01:00:00');
        SlotTime="60:00"
    }
    else {
        SlotConvertTime = converthourstoseconds('00:' + SlotTime + ':00');
        SlotTime = '00:' + SlotTime;
    }
    var startTime = moment(from_time, 'hh:mm');
    var endTime = moment(to_time, 'hh:mm');

    var totalSec = endTime.diff(startTime, 'seconds');

    var hours = parseInt(totalSec / 3600) % 24;
    var minutes = parseInt(totalSec / 60) % 60;
    var seconds = totalSec % 60;

    var total_fixed_time = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
   
    total_fixed_time = converthourstoseconds(total_fixed_time);
    console.log('total_fixed_time----' + total_fixed_time)
    var totslotcount = total_fixed_time / SlotConvertTime;

    var indiSlotETime = from_time;
    var indiSlotSTime = from_time;
    console.log('totslotcount--------'+totslotcount);
    console.log('indiSlotETime------' + indiSlotETime);
    console.log((converthourstoseconds(indiSlotETime + ":00") + ' ------- ' + converthourstoseconds(to_time + ":00")));
    
    for (i = 0; i < totslotcount; i++) {
        console.log('(indiSlotETime, SlotTime)-----' + (indiSlotETime + '-------------' + SlotTime));
        indiSlotETime = addTimes(indiSlotETime, SlotTime);
        console.log(indiSlotETime);
        if (converthourstoseconds(indiSlotETime + ":00") <= converthourstoseconds(to_time + ":00")) {
            console.log('indiSlotETime-' + i + ' ------' + indiSlotETime);
            var Rschedule_date1=Rschedule_date + " " + indiSlotSTime;
            var Rschedule_date2 = Rschedule_date + " " + indiSlotETime;
            var doctorScheduleId1 = doctorScheduleId;
            console.log('SlotData-' + i + ' ------' + Rschedule_date1 + ',' + Rschedule_date2 + ',' + doctorScheduleId1);
            var SlotData = {

                doctor_schedule_id: doctorScheduleId,
                slot_start_time: Rschedule_date + " " + indiSlotSTime + ":00",
                slot_end_time: Rschedule_date + " " + indiSlotETime + ":00",
                doctor_appointment_slot_status: "3",
                Dml_Indicator: "I",
            }
            console.log('SlotData-' + i + ' ------' + SlotData);
            var a=0;
            var tot = totslotcount;
            $.ajax({
                async: true,
                type: 'POST',
                url: '/CalendarConfiguration/DoctorAppointmentSlot',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(SlotData),
                success: function (data) {
                    console.log(a);
                    console.log('done');
                    console.log('tot------------' + tot);
                    console.log('totdayCount------------' + totdayCount);
                    console.log('ajaxroundcount------------' + ajaxroundcount);
                    if (a == tot - 1 && totdayCount == ajaxroundcount) {
                        toastr.success('Completed');
                        //window.location.href = '/CalendarConfigurationList/';
                    }
                    return a++;

                }

            });           
        }
        indiSlotSTime = indiSlotETime;
        //console.log('i vali-------' + a + 'totval-----------' + totslotcount);
        
        //if (a == (totslotcount - 1)) {

        //    redirect = 1;
        //    return redirect;
        //    console.log('redirect enter');
        //}
        
    }
    
}