"use strict";

import { Controller } from 'stimulus';
import Cookies from 'js-cookie';

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="changeRegion" attribute will cause
 * this controller to be executed. The name "changeRegion" comes from the filename:
 * changeRegion_controller.js -> "changeRegion"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        var currentUrl = new URL(window.location);

        if (currentUrl.searchParams.get('region') !== null) {
            Cookies.set('region', currentUrl.searchParams.get('region'), {expires: 1});
            currentUrl.searchParams.delete('region');
            location.replace(currentUrl);
        }

        var checkboxes = this.element.querySelectorAll('input');
        this.element.querySelector('button.submit').addEventListener('click', function() {
            checkboxes.forEach(function(el) {
                if (el.checked) {
                    origin = currentUrl.origin.split('.');
                    origin[1] = (el.value == '94')? 'wmtmed' : 'sovamed';
                    currentUrl.search = 'region=' + el.value
                    Cookies.set('region', el.value, {expires: 1});
                    location.replace(origin.join('.') + currentUrl.pathname + currentUrl.search + location.hash);
                }
            });
        });

        if (/sovamed\.ru/m.test(location.hostname)) {
            if (typeof Cookies.get('region') === 'undefined' || Cookies.get('region') == '94') {
                $('#chengeRegion').modal('show');
            }
        } else {
            Cookies.set('region', 94, {expires: 1});
        }

        if (Cookies.get('region')) {
            var item = this.element.querySelector('#regionItem' + Cookies.get('region'));
            item.checked = true;

            if (document.getElementById('regionName')) {
                document.getElementById('regionName').innerText = item.dataset.text;
            }
        }

        $('#chengeRegion').on('hide.bs.modal', function (e) {
            if (!Cookies.get('region')) {
                if (/sovamed\.ru/m.test(location.hostname)) {
                    Cookies.set('region', 91, {expires: 1});
                } else {
                    Cookies.set('region', 94, {expires: 1});
                }
            }
        })
    }
}
