
import ApiQuery from '../Tools/ApiQuery'


export default class AuthServices {

    constructor() {

        this.URL_Auth = "api/Auth/Auth";
        this.URL_UserInfo = "api/Auth/UserInfo"

        this.AuthCoockieName = "AuthToken";
    }

    async AuthAsync(login, password) {

        return await ApiQuery(this.URL_Auth, "Post",
            {
                Login: login,
                Password: password
            }).then(function (data) {
                if (data.Successe) {
                    this._SetTocken(data.Token);
                }
                else {
                    this._SetTocken("");
                }

                return data;
            }.bind(this));
    }

    Logout() {
        this._SetTocken("");
    }


    async GetUserInfoAsync() {
        return await ApiQuery(this.URL_UserInfo, "Post")
            .then(function (data) {
                if (data.Successe) {
                    this._SetTocken(data.Token);
                }
                else {
                    this._SetTocken("");
                }

                return data;
            }.bind(this));
    }


    //Возвращает true если пользователь авторизован
    IsAuth() {
        let token = this._GetTocken();
        return token != "";
    }


    _getCookie(name) {
        let matches = document.cookie.match(new RegExp(
            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
        ));
        return matches ? decodeURIComponent(matches[1]) : "";
    }

    //Токен авторизации
    _GetTocken() {
        return this._getCookie(this.AuthCoockieName);
    }
    //задать токен
    _SetTocken(val) {
        document.cookie = this.AuthCoockieName + "=" + val;
    }

}
