$(document).ready(function () {
    fcm_notification();
});

$("#btnSignIn").click(function () {
    debugger;
    var Did = '', doctor_user_module_id = '', doctor_user_role_rights = '', lab_id='',referral_code_id='',module_path='';
    var RoleId, HospitalId,HospitalIdInt,Hospital_branch_id,subdepartmentid,departmentid,branch_name,department_name,subdepartment_name,Formbuilder_id,casesheet_print_type,default_medicine_store;
    if ($('#txtusername').val() == "") {
        $('#Ptxtusername').show();
        $('#Ptxtusername').fadeOut(8000);
        $('#Ptxtusername').html('Enter Your registered email address');
        $('#txtusername').focus();
        return false;
    }
    if ($('#txtPassword').val() == "") {
        $('#PtxtPassword').show();
        $('#PtxtPassword').fadeOut(8000);
        $('#PtxtPassword').html('Enter Password');
        $('#txtPassword').focus();
        return false;
    }
    
    if ($.trim($('#txtusername').val()).length > 0 && $.trim($('#txtPassword').val()).length > 0) {
        var LoginData = {
            doctor_user_name: $("#txtusername").val(),
            doctor_user_password: $("#txtPassword").val(),
            fcm_token: $('#fcm_token').val(),
            application_type: "1"
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Home/LoginVerification',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(LoginData),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                console.log(data);
                if(data.msg=="Success"){
                    var token=data.token;
                    var data=data.data;
                    if (jQuery.isEmptyObject((data))) {
                        $('#PPbtnSignIn').show();
                        $('#PPbtnSignIn').fadeOut(8000);
                        $('#PPbtnSignIn').html('please enter valid username and password');
                    }
                    else {
                        debugger;
                        var product_code='';
                        var subscription_start_date='';
                        var subscription_end_date='';
                        var no_of_license='';
                        var admin_doctor_id = '';
                        var hospital_module = '';
                        var casesheet_type ='';
                        var token1=token;
                        var usermailid='';
                        console.log(token1);

                        if(data.Table[0].hospital_status==2)
                        {
                            $('#PbtnSignIn').show();
                            $('#PbtnSignIn').fadeOut(8000);
                            $('#PbtnSignIn').html("Hospital has been inactive please contact the Mocero Support Team");
                            return false;
                        }

                        else if(data.Table[0].branch_status==2){
                            $('#PbtnSignIn').show();
                            $('#PbtnSignIn').fadeOut(8000);
                            $('#PbtnSignIn').html("Branch has been inactive please contact the Mocero Support Team");
                            return false;
                        }
                        else if (data.Table1.length <= 0)
                        {
                            $('#PPbtnSignIn').show();
                            $('#PPbtnSignIn').fadeOut(8000);
                            $('#PPbtnSignIn').html('please enter valid username and password');
                            return false;
                        }

                        if (data.Table1.length > 0) {
                            debugger;
                            for (var i = 0; i < data.Table1.length; i++) {
                                Did = data.Table1[i].doctor_id;
                                RoleId = data.Table1[i].doctor_user_role_id;
                                var UserId = data.Table1[i].doctor_user_id;
                                HospitalId = data.Table1[i].hospital_id;
                                HospitalIdInt = data.Table1[i].hospitalid;
                                Hospital_branch_id=data.Table1[i].branch_id;
                                subdepartmentid=data.Table1[i].subdepartment;
                                departmentid=data.Table1[i].department;
                                branch_name=data.Table1[i].branch_name;
                                department_name=data.Table1[i].department_name;
                                subdepartment_name=data.Table1[i].subdepartment_name;

                                usermailid=data.Table1[0].useremail_id;
                                Formbuilder_id=data.Table1[0].is_formbuilder;

                                casesheet_print_type = data.Table1[0].casesheet_print_type;
                                is_pharmacy = data.Table1[0].is_pharmacy;
                                default_medicine_store = data.Table1[0].default_medicine_store;


                                //alert(Did);
                            }
                            if(data.Table5.length>0)
                            {
                                product_code = data.Table5[0].product_code;
                                //product_code=2;
                                subscription_start_date = data.Table5[0].subscription_start_date;
                                subscription_end_date = data.Table5[0].subscription_end_date;
                                no_of_license = data.Table5[0].no_of_license;
                                if(product_code!='' && product_code !=null) {
                                    if(product_code==2 || product_code==3){
                                        if (window.location.href.indexOf("curola") < 0) {
                                            $('#PbtnSignIn').show();
                                            $('#PbtnSignIn').fadeOut(8000);
                                            $('#PbtnSignIn').html('Login Succesfully');
                                            //return false;
                                        }
                                    }
                                    else{
                                        if (window.location.href.indexOf("ursugar") < 0) {
                                            $('#PbtnSignIn').show();
                                            $('#PbtnSignIn').fadeOut(8000);
                                            $('#PbtnSignIn').html('Login Succesfully');
                                            //return false;
                                        }
                                    }
                                }

                                admin_doctor_id = data.Table5[0].admin_doctor_id;
                                referral_code_id = data.Table5[0].referral_code_id;
                                casesheet_type = data.Table5[0].casesheet_type;
                            }
                            if (data.Table7.length > 0) {
                                for (var i = 0; i < data.Table7.length; i++) {
                                    hospital_module = hospital_module + data.Table7[i].module_id + ',';
                               
                                }
                            }
                            for (var i = 0; i < data.Table2.length; i++) {
                                doctor_user_module_id =doctor_user_module_id + data.Table2[i].doctor_user_module_id+',';
                                doctor_user_role_rights = doctor_user_role_rights + data.Table2[i].doctor_user_role_rights+',';
                                module_path =module_path + data.Table2[i].module_path+',';
                                //lab_id = data.Table1[i].lab_id;
                                lab_id = "";
                            }
                            if (data.Table4.length > 0) {
                                for (var i = 0; i < data.Table4.length; i++) {
                                    //login_details = data.Table4[i].doctor_name + '$' + data.Table4[i].doctor_id + '$' + data.Table4[i].speciality_name + '$' + data.Table4[i].photo + '$' + data.Table4[i].designation
                                    login_details = data.Table4[i].doctor_name + '$' + data.Table4[i].doctor_id + '$' + data.Table4[i].speciality_name + '$' + data.Table4[i].photo + '$' + data.Table4[i].designation + '$' + data.Table4[i].first_name1
                                }
                            }
                            else {
                                for (var i = 0; i < data.Table3.length; i++) {
                                    //login_details = data.Table3[i].doctor_name + '$' + data.Table3[i].doctor_id + '$' + data.Table3[i].speciality_name + '$' + data.Table3[i].photo + '$' + data.Table3[i].designation
                                    login_details = data.Table3[i].doctor_name + '$' + data.Table3[i].doctor_id + '$' + data.Table3[i].speciality_name + '$' + data.Table3[i].photo + '$' + data.Table3[i].designation + '$' + data.Table3[i].first_name1
                                }
                            }

                            if (data.Table5.length > 0) {
                                login_details = login_details + '$' + data.Table5[0].classification + '$' + data.Table5[0].officer_id;
                            }

                            //document.cookie = doctor_user_module_id = doctor_user_module_id, doctor_user_role_rights = doctor_user_role_rights, lab_id = lab_id, expires='Wed, 08 jan 2020 12:00:00 UTC';
                            var LoginData = {
                                doctor_id: Did,
                                doctor_user_name: $("#txtusername").val(),
                                //doctor_user_name: usermailid,
                                doctor_user_role_id: RoleId,
                                doctor_user_id: UserId,
                                hospital_id: HospitalId,
                                HospitalId: HospitalIdInt,
                                doctor_user_module_id: doctor_user_module_id,
                                doctor_user_role_rights: doctor_user_role_rights,
                                lab_id: lab_id,
                                login_details: login_details,
                                product_code : product_code,
                                subscription_start_date : subscription_start_date,
                                subscription_end_date : subscription_end_date,
                                no_of_license : no_of_license,
                                admin_doctor_id: admin_doctor_id,
                                referral_code_id: referral_code_id,
                                hospital_module: hospital_module,
                                module_path:module_path,
                                casesheet_type: casesheet_type,
                                token:token1,
                                Hospital_branch_id:Hospital_branch_id,
                                subdepartmentid:subdepartmentid,
                                departmentid:departmentid,
                                branch_name:branch_name,
                                department_name:department_name,
                                subdepartment_name:subdepartment_name,

                                hs_logo:data.Table[0].hospital_logo,
                                hs_favicon:data.Table[0].hospital_favicon,
                                hs_color_code:data.Table[0].color_code,
                                hs_name:data.Table[0].hospital_name,
                                formbuilder_id:Formbuilder_id,
                                casesheet_print_type :  casesheet_print_type,
                                is_pharmacy: is_pharmacy,
                                default_medicine_store: default_medicine_store
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/Home/LoginSession',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(LoginData),
                                success: function (data) {
                                    debugger;
                                   
                                    window.location = "Dashboard?UId=" + btoa($.trim($('#txtusername').val())) + "&DId=" + btoa(Did + "&Role=" + btoa(RoleId));
                                }
                            });
                        }
                    }                    
                }
                else{
                    console.log(data);
                }
            }

        });
    }
});


$('#txtPassword').keypress(function (e) {
    var key = e.which;
    if (key == 13)  // the enter key code
    {
        $('#btnSignIn').click();
    }
});

$('#txtusername').keypress(function (e) {
    var key = e.which;
    if (key == 13)  // the enter key code
    {
        $('#btnSignIn').click();
    }
});


//fcm push notification

function fcm_notification()
{
    firebase.initializeApp({
        apiKey: "AIzaSyDp0MDxzY_RWj2xyLW67cYpjZLNaVcaYcE",
        authDomain: "sight-sg.firebaseapp.com",
        databaseURL: $('#HFirebaseID').val(),
        projectId: "sight-sg",
        storageBucket: "sight-sg.appspot.com",
        messagingSenderId: "142098889845",
        appId: "1:142098889845:web:c47e8485558d9a6b3a4c3c",
        measurementId: "G-E2DZP9XEXT"
    });

    const messaging = firebase.messaging();

    messaging.usePublicVapidKey('BKMn9wSkLibV8j9KYjqWR3he5O6p6XrjxQVyKeJaogkOTQC2nuGHkMWkeH2pbeES5h5FWnRYptYgGFIpvnTrra4');

    messaging.onTokenRefresh(() => {
        messaging.getToken().then((refreshedToken) => {

        }).catch((err) => {
            console.log('Unable to retrieve refreshed token ', err);
        });
    });

    messaging.onMessage((payload) => {
        let { title, body} = payload.notification;
        showNotification(title,body);
        console.log('Message received. ', payload);
    });

    messaging.getToken().then((currentToken) => {
        if (currentToken) {
            console.log(currentToken);
            $('#fcm_token').val(currentToken);
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
    });
}

function showNotification(title, body) { 
    var d, n;
    d = new Date();
    n = d.getTime();
    icon = "/Content/img/logo-icon.png?t= "+ n +""
    var notification = new Notification(title, { body, icon });
    notification.onclick = () => { 
        notification.close();
        window.parent.focus();
    }
}