
let button_read_mykad = document.getElementById("button_read_mykad");
let button_close_modal = document.querySelector("#daftar_pelanggan_mykad_reader button.btn.btn-danger");
let original_photo_loader = document.querySelector("#photo-mykad").src;

    let showLoader = () => {
      let pageLoader = document.getElementById('page_loader');
      pageLoader.removeAttribute('class');
      pageLoader.classList.add('loading');
    };

    let hideLoader = () => {
      let pageLoader = document.getElementById('page_loader');
      pageLoader.removeAttribute('class');
    };

    function handleMyKadReader()
    {
        showLoader();
		WebSocketManager.init("wss://localhost:5963/mykadwebsocket");
        WebSocketManager.listReader(callbackDoneGetListCardReader);
    }

    function callbackDoneGetListCardReader(data, respcode)
	{
        console.log('done get list card reader');

        if(respcode === -1){
            console.log({'location': 'callbackDoneGetListCardReader', 'data' : data} );
        }

        let isDevicesConnected = Object.keys(data).length > 0;

        if(! isDevicesConnected){
           hideLoader();

           Swal.fire({ icon: 'error', title: 'Pembaca MyKad tidak dapat dikesan, sila periksa sambungan', });

           return;
        }

		let slots = data.toString().split(',');
        WebSocketManager.open(doneOpenReaderConnection, slots[0]);
	}

    function doneOpenReaderConnection()
	{
		WebSocketManager.readAllText(callBackAfterReadMykad);
    }

    function handleMyKadReaderError(sw12AndApiName)
    {
        hideLoader();

        let error_handler_dictionary = {
            '0x80100069' : 'Tiada MyKad dikesan, sila masukkan Mykad untuk dibaca',
            '0x80100066' : 'MyKad mungkin dimasukkan terbalik, sila masukkan dengan betul',
            'default' : sw12AndApiName,
        };

        let error_data = sw12AndApiName.split(" ");

        let error_code = error_data.filter(x => x.startsWith('0x')).splice(-1)

        let error_message = error_handler_dictionary['default'];

        let hasDefinedError = error_handler_dictionary.hasOwnProperty(error_code);

        if(hasDefinedError){
            error_message = error_handler_dictionary[error_code];
        }

        Swal.fire({ icon: 'error', title: error_message, });
    }

    function callBackAfterReadMykad(data, respcode, sw12AndApiName)
	{
        if(respcode !== 0){
            handleMyKadReaderError(sw12AndApiName);
            return
        }

        checkIfMyKadExists(data.IDNum)
            .then(response => {
                let isResponseArray = Array.isArray(response);
                resolved_response = isResponseArray ? response.pop() : response;

                if (resolved_response === 'no-data') {
                    populateDaftarPelangganModal(data, handleReadPhoto);
                } else {
                    let input_search_noic = document.getElementById("noic");
                    let form_search_noic = document.querySelector("form[name='frmsearch']");

                    let getMyKadNumberWithoutHypens = myKadNumber => myKadNumber.replace(/-/g, '');
                    input_search_noic.value = getMyKadNumberWithoutHypens(data.IDNum);
                    form_search_noic.submit();
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: error,
                });
            });

        hideLoader();
	}

    function checkIfMyKadExists(myKadNumber) {
        let myKadNumberWithoutHyphens = myKadNumber.replace(/-/g, '');

        const url = wakil_caricustomer_endpoint + '/?icno=' + myKadNumberWithoutHyphens;

        const connectionConfig = {
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": document.querySelector('input[name="_token"]').value
            },
            credentials: "same-origin",
        };

        return fetch(url, connectionConfig)
            .then(response => response.json())
    }

    let populateDaftarPelangganModal = (data, callbackAfterPopulateDaftarPelanggan) => {
        $('#daftar_pelanggan_mykad_reader').modal('show');
        let modal_form = document.querySelector("#daftar_pelanggan_mykad_reader .modal-body .row.form-group");

        const religions = [
            ['01', 'Islam'],
            ['02', 'Hindu'],
            ['03', 'Buddha'],
            ['04', 'Kristian'],
            ['05', 'Lain-lain'],
        ];

        const races = [
            ['M', 'Melayu'],
            ['C', 'Cina'],
            ['I', 'India'],
            ['L', 'Lain-lain'],
        ];

        let getCodeFromValue = (needle, haystack) => {
            let title_cased_text = needle.split(' ')
                .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
                .join(' ');

            return haystack.filter(x => x[1] == title_cased_text)[0][0];
        };

        let getMyKadNumberWithoutHypens = (IDNum) => {
            return IDNum.replace(/-/g, '');
        }

        let getFormattedDateOfBirth = (date_of_birth) => {

            let date_of_birth_hyphenated = date_of_birth.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");

            const [year, month, day] = date_of_birth_hyphenated.split('-');
            return day + '/' + month + '/' + year;
        };

        let getAgeFromDateOfBirth = (date_of_birth) => {

            let date_of_birth_hyphenated = date_of_birth.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");

            const [birth_year, birth_month, birth_day] = date_of_birth_hyphenated.split('-');

            let formatBirthMonth = (birth_month) => {
                let newbirthMonth = birth_month < 9 ? birth_month[1] : birth_month;
                return newbirthMonth;
            };

            const count_leap_year = countLeapYears(birth_year, formatBirthMonth(birth_month), birth_day) - 1;

            const start = new Date(date_of_birth_hyphenated),
                end = new Date(),
                diff = new Date(end - start),
                days = ((diff / 1000 / 60 / 60 / 24) - count_leap_year) / 365;

            return parseInt(days);
        };

        let getBumiputeraStatus = (race) => {

            const non_bumiputera_ethnicity = ['INDIA', 'CINA'];

            let isBumiputera = !non_bumiputera_ethnicity.includes(race);

            return isBumiputera;
        };

        let disablePointerEventsOnClickableInputs = () => {
            modal_form.querySelector("input[name='bumiputera']").style.pointerEvents = 'none';
            modal_form.querySelector("input[name='warganegara']").style.pointerEvents = 'none';

            modal_form.querySelector("select[name='bangsa']").style.pointerEvents = 'none';
            modal_form.querySelector("select[name='agama']").style.pointerEvents = 'none';
        }

        let mykad_modal = document.querySelector("#daftar_pelanggan_mykad_reader");
        let photo_container = mykad_modal.querySelector("#photo-mykad-container");

        modal_form.querySelector("textarea[name='name']").value = data.OrgName;
        modal_form.querySelector("input[name='noic']").value = getMyKadNumberWithoutHypens(data.IDNum);
        modal_form.querySelector("input[name='tarikh_lahir']").value = getFormattedDateOfBirth(data.BirthDate);
        modal_form.querySelector("input[name='negeri_lahir']").value = data.BirthPlace;
        modal_form.querySelector("input[name='jantina']").value = data.Gender == 'LELAKI' ? 'Lelaki' : 'Perempuan';
        modal_form.querySelector("input[name='warganegara']").checked = data.Citizenship === 'WARGANEGARA' ? true : false;
        modal_form.querySelector("input[name='bumiputera']").checked = getBumiputeraStatus(data.Race);
        modal_form.querySelector("select[name='agama']").value = getCodeFromValue(data.Religion, religions);
        modal_form.querySelector("textarea[name='alamat']").value = [data.Address1, data.Address2, data.Address3].join(", ");

        let getPostCode = (postCodeCity) => postCodeCity.replace(/\D/g, '');
        modal_form.querySelector("input[name='poskod']").value = getPostCode(data.PostcodeCity);

        let getCityName = (postCodeCity) => postCodeCity.replace(/\d/g, '');
        modal_form.querySelector("input[name='daerah']").value = getCityName(data.PostcodeCity).trim();

        modal_form.querySelector("input[name='negeri']").value = data.State;
        modal_form.querySelector("input[name='age']").value = getAgeFromDateOfBirth(data.BirthDate);
        modal_form.querySelector("select[name='bangsa']").value = getCodeFromValue(data.Race, races);

        calculatePassportAge();

        photo_container.classList.remove('d-none');
        photo_container.classList.add('d-flex');

        $('#daftar_pelanggan_mykad_reader').modal('show');


        disablePointerEventsOnClickableInputs();
        callbackAfterPopulateDaftarPelanggan();
}


function handleReadPhoto()
{
	WebSocketManager.init("wss://localhost:5963/mykadwebsocket");
    WebSocketManager.listReader(callbackDoneGetListCardReader2);
}

function callbackDoneGetListCardReader2(data, respcode)
{
    if(respcode === -1){
        console.log({'location': 'callbackDoneGetListCardReader', 'data' : data} );
    }

    let slots = data.toString().split(',');
    WebSocketManager.open(doneOpenReaderConnection2, slots[0]);
}

function doneOpenReaderConnection2()
{
    WebSocketManager.readPhoto(callbackAfterReadPhoto2);
}

function callbackAfterReadPhoto2(data, RespCode, RespSW12AndApiName)
{
    let mykad_modal = document.querySelector("#daftar_pelanggan_mykad_reader");
    let photo = mykad_modal.querySelector("#photo-mykad");

    let isDataEmpty = data
    && Object.keys(data).length === 0
    && Object.getPrototypeOf(data) === Object.prototype;

    if(isDataEmpty){
        photo.src = original_photo_loader;
        return;
    }

    photo.src = 'data:image/jpeg;base64, ' + data.Base64Photo;
}

let hideMykadPhoto = () => {

    WebSocketManager.close(() => console.log('Websocket closed'));

    let photo = document.getElementById("photo-mykad");
    let photo_container = document.getElementById("photo-mykad-container");

    photo.src = original_photo_loader;

    photo_container.classList.add('d-none');
    photo_container.classList.remove('d-flex');
};

button_read_mykad.addEventListener("click", handleMyKadReader);
button_close_modal.addEventListener("click", hideMykadPhoto);
