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="setting" attribute will cause
 * this controller to be executed. The name "setting" comes from the filename:
 * setting_controller.js -> "setting"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        loader.loadSDK('setting');
    }

    submit() {
        var plainPassword = document.getElementById('setting_plainPassword');
        var settingToken = document.getElementById('setting__token');

        window.webSDK.clientModify({
            'password': plainPassword.value
        }).then(function(resolve) {
            if (resolve.success) {
                $.ajax({
                    method: "POST",
                    crossDomain: false,
                    url: "/setting",
                    contentType: "application/x-www-form-urlencoded",
                    dataType: "json",
                    data: {
                        'setting': {
                            '_token': settingToken.value,
                            'plainPassword': plainPassword.value
                        }
                    },
                    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 (error) {
            helper.sendRequest({
                data: {'error': error, method: 'clientModify'}
            }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
            
            console.log(error)
            var msg = document.getElementById('msg');
            var div = document.createElement('div');
            div.classList = 'alert alert-danger';
            msg.innerHTML = '';
            msg.append(div);
            
            if (error.data.password) {
                var p = document.createElement('p');
                p.innerHTML = error.data.password[0];
                div.append(p);
            } else if (error.data['password.password'][0]) {
                var p = document.createElement('p');
                p.innerHTML = error.data['password.password'][0];
                div.append(p);
            }
        });
    }
    
}
