import {observer} from "mobx-react";
import {action, makeObservable, observable, reaction, runInAction} from "mobx";
import {Page} from "../custom/layout/Page";
import {IAuthenticated} from "../../models/user";
import {DataTable} from "../custom/DataTable";
import {get} from "../../utils/request";
import {Column, TableDescriptor} from "../../utils/tables";

@observer
export class UserListPage extends Page {
    constructor(props: {}) {
        super(props);
        makeObservable(this);
    }

    componentDidMount() {
        this.requestUsers();
        reaction(() => this.users, () => {
            if (typeof this.users === 'undefined') {
                return;
            }

            this.tableDescriptor = new TableDescriptor(this.userColumns, this.users);
        }, {fireImmediately: true});
    }

    @observable users?: IAuthenticated[];
    @observable tableDescriptor?: TableDescriptor<IAuthenticated>;

    userColumns = [
        new Column('login', 'Логин'),
        new Column('fullName', 'Полное имя'),
        new Column('email', 'Email'),
        new Column('phone', 'Телефон'),
        new Column('createdAt', 'Дата создания'),
        new Column('updatedAt', 'Дата обновления', (value: string) => value ? value : 'Не обновлялось'),
    ];


    @action.bound
    requestUsers() {
        this.thinkStore.think('userList');
        get<IAuthenticated[]>('user/get-all').then((users) => {
            runInAction(() => {
                this.users = users;
            });
        }).finally(() => {
            this.thinkStore.completeAll('userList');
        });
    }

    get page() {
        return <>
            {
                this.tableDescriptor &&
                <DataTable tableDescriptor={this.tableDescriptor} name={'Пользователи'}/>
            }
        </>
    }
}