class AccountManager {
    // Classe pour gérer la partie "compte" de K-Psul
    // Devrait être la seule interface entre le JS de K-Psul et la logique des comptes.
    constructor() {
        // jQuery elements
        this._$input = $("#id_trigramme");
        this._$container = $("#account");
        this._$article_select = $("#article_autocomplete")

        // Subordinated classes
        this.account = new Account({ "trigramme": "" });
        this.search = new AccountSearch(this)

        // Initialization
        this._init_events();
    }

    get data() {
        return this.account.toJSON();
    }

    _init_events() {
        var that = this;

        // L'input change ; on met à jour le compte
        this._$input.on("input", () => this.update())

        // Raccourci LIQ
        this._$input.on("keydown", function (e) {
            if (e.key == "ArrowDown") {
                that.set("LIQ")
            }
        })

        // Fonction de recherche
        this._$container.on('click', '.search', function () {
            that.search.open();
        });

        this._$container.on('keydown', function (e) {
            if (e.key == "f" && e.ctrlKey) {
                // Ctrl + F : universal search shortcut
                that.search.open();
                e.preventDefault();
            }
        });
    }

    set(trigramme) {
        this._$input.val(trigramme);
        this.update();
    }

    update() {
        var trigramme = this._$input.val().format_trigramme();
        this.account.set({ "trigramme": trigramme })
        if (trigramme.is_valid_trigramme()) {
            this.account.fetch({
                "success": this._on_success.bind(this),
                "error": this.reset.bind(this, false),
            })
        } else {
            this.reset()
        }
    }

    _on_success() {
        // On utilise l'objet global window pour accéder aux fonctions nécessaires
        this.account.render();
        this._$article_select.focus();
        window.updateBasketAmount();
        window.updateBasketRel();
    }

    reset(hard_reset = false) {
        this.account.reset();
        this.account.render();

        if (hard_reset) {
            this._$input.val("");
            this.update()
        }
    }
}

class AccountSearch {

    constructor(manager) {
        this.manager = manager;

        this._content = '<input type="text" name="q" id="search_autocomplete" autocomplete="off" spellcheck="false" autofocus><div id="account_results"></div>';
        this._input = '#search_autocomplete';
        this._results_container = '#account_results';

    }

    open() {
        var that = this;
        this._$dialog = $.dialog({
            title: 'Recherche de compte',
            content: this._content,
            backgroundDismiss: true,
            animation: 'top',
            closeAnimation: 'bottom',
            keyboardEnabled: true,
            onOpen: function () {
                that._$input = $(that._input);
                that._$results_container = $(that._results_container);
                that._init_form()
                    ._init_events();
            },
        });
    }

    _init_form() {
        var that = this;

        this._$input.yourlabsAutocomplete({
            url: django_urls['kfet.account.search.autocomplete'](),
            minimumCharacters: 2,
            id: 'search_autocomplete',
            choiceSelector: '.autocomplete-value',
            placeholder: "Chercher un utilisateur K-Fêt",
            container: that._$results_container,
            box: that._$results_container,
            fixPosition: function () { },
        });

        return this;
    }

    _init_events() {
        this._$input.bind('selectChoice',
            (e, choice, autocomplete) => this._on_select(e, choice, autocomplete)
        );
        return this;
    }

    _on_select(e, choice, autocomplete) {
        // Une option est de la forme "<User> (<trigramme>)"
        var choice_text = choice.text().trim();
        var trigramme_regex = /\((.{3})\)$/;
        // le match est de la forme [<global match>, <group match>]
        trigramme = choice_text.match(trigramme_regex)[1]
        this.manager.set(trigramme);
        this.close();
    }

    close() {
        if (this._$dialog !== undefined) {
            this._$dialog.close();
        }
    }
}
