import { Controller } from 'stimulus';
const loader = require("./../components/loader.js");
const helper = require("./../components/helper.js");

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="default" attribute will cause
 * this controller to be executed. The name "default" comes from the filename:
 * default_controller.js -> "default"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        loader.loadSDK('system').then(function(webSDK) {
            webSDK.on('init', function() {
                if (this.data.user.authenticated) {
                    runWebSDK(webSDK);           
                }
            });
        })
        
        let runWebSDK = function (webSDK) {
            this.showNamePatient(webSDK.data.user.fullName);
            this.element.addEventListener('click', function () {
                this.changeResponsible(webSDK);            
            }.bind(this))
        }.bind(this)
        
        $(popup).on('hidden.bs.modal', function () {
            this.querySelector('.modal-title').innerHTML = '';
            this.querySelector('.modal-dialog').classList.add('modal-lg');
            this.querySelector('.modal-body').innerHTML = '';
            
            if (this.querySelector('.modal-footer')) {
                this.querySelector('.modal-footer').remove();
            }
        });
    }

    showNamePatient(fullName) {
        document.getElementById('fullName').innerHTML = fullName;
    }

    changeResponsible(webSDK) {
        var popup = document.getElementById('popup'); 
            popup.querySelector('.modal-title').innerHTML = 'Выбор пациента';
            popup.querySelector('.modal-dialog').classList.remove('modal-lg');
        
        var popupBody = document.getElementById('popup-body');
            popupBody.innerHTML = '';
            
        webSDK.data.user.represents.forEach(function (represent) {
            var div = document.createElement('div');
                div.classList = 'form-check';

            var input = document.createElement('input');
                input.id = represent.pcode;
                input.classList = 'form-check-input';
                input.value = represent.pcode;
                input.type = "radio";
                input.name = "changePatient";

                if (webSDK.data.user.representId == represent.pcode) {
                    input.checked = 'true';
                }

                div.append(input);

            var label = document.createElement('label');
                label.setAttribute('for', represent.pcode);
                label.classList = 'form-check-label';
                label.innerHTML = represent.fullName;
                div.append(label);

            popupBody.append(div);

        });

        var div = document.createElement('div');
            div.classList = 'modal-footer';

        var button = document.createElement('button');
            button.classList = 'btn btn-outline-secondary';
            button.innerHTML = 'Выбрать';
            button.addEventListener('click', function() {
                loader.btnLoader(this, true);
                window.webSDK.selectClient({
                    id: document.querySelector('input[name="changePatient"]:checked').value
                }).then(function (user) {
                    $.ajax({
                        method: "POST",
                        crossDomain: false,
                        url: "/api/authenticated",
                        contentType: "application/x-www-form-urlencoded",
                        dataType: "json",
                        data: {
                            user: user,
                            uid: user.id
                        },
                        success(response) {
                            if (response.data.success == true) {
                                var parser = document.createElement('a');
                                    parser.href = response.data.redirect;

                                window.location.replace(document.location.origin + parser.pathname + parser.search);
                            }
                        }
                    });
                }).catch(function (e) {
                    helper.sendRequest({
                            data: {'error': e, method: 'selectClient'}
                        }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                })
            });

        div.append(button);
        popup.querySelector('.modal-content').append(div);
        
        $(popup).modal('show');
    }
}
