import React from "react";
import Column from "../../../../components/common/columns";
import { Paginated } from "../../../../services/Paginated";
import { MakeGeneralIdRef } from "../../../../utils/GeneralIdRef";
import withRouter, { RouterProps } from "../../../../utils/withRouter";
import UserRolesTable from "./UserRolesTable";
import roleService, { RoleUser } from "../serrvices/rolesService";
import Button, { ButtonType } from "../../../../components/common/Button";
import Loading from "../../../../components/common/Loading";
import Permission from "../../../../components/common/Permission";

interface UserRoleEditorState{
    loaded: boolean,
    pagedData : Paginated<RoleUser>,
    sortColumn : Column<RoleUser>,
    filters: Map<string, string>;
}

interface UserRoleEditorProps extends RouterProps{
    role : any | undefined
}

class UserRoleEditorNoRouter extends React.Component<UserRoleEditorProps, UserRoleEditorState> {
    state : UserRoleEditorState = {
        loaded : false,
        pagedData : { page: 1,
            pageSize : 10,
            count: 0,
            totalPages: 1,
            data: [] },
        sortColumn: { key: "name", label: "Name", order: "asc" },
        filters: new Map<string, string>()
    }

    componentDidMount = async () => {
        const { page, pageSize } = this.state.pagedData;

        await this.changePage(page, pageSize);
    }

    async componentDidUpdate(prevProps: Readonly<UserRoleEditorProps>, prevState: Readonly<UserRoleEditorState>, snapshot?: any) {
        if (prevProps.role?.id !== this.props.role?.id) {
            this.componentDidMount();
        }
    }

     changePage = async(page: number, pageSize : number) =>{
        const { sortColumn, filters } = this.state;

        await this.getRoleUsers(page, pageSize, sortColumn, filters);
    }

    onSort = async(sortColumn : Column<RoleUser>) => {
        const {page, pageSize } = this.state.pagedData;
        const { filters } = this.state;

        await this.getRoleUsers(page, pageSize, sortColumn, filters);
    }

    onSearch = async ( name: string, value: string) => {
        const {page, pageSize } = this.state.pagedData;
        const {sortColumn, filters } = this.state;
        filters.set(name, value);

        await this.getRoleUsers(page, pageSize, sortColumn, filters);
    };

    getRoleUsers = async ( page : number, pageSize : number, sortColumn : Column<RoleUser>, filters : Map<string, string>) => {

        const { role } = this.props;
        const roleGeneralIdRef = MakeGeneralIdRef( role?.id, role?.guid);        
        const pagedData = await roleService.getRoleUsers(page, pageSize, sortColumn.key, sortColumn.order === "asc", roleGeneralIdRef, filters);
        if (pagedData) {
            this.setState({ loaded: true, filters, pagedData, sortColumn });
        }
        else {
            this.setState({ loaded: false });
        }
    }

    onDelete = async ( user? : RoleUser) => {
        const { role } = this.props;

        const roleId = MakeGeneralIdRef(role?.id, role?.guid);
        const userId = MakeGeneralIdRef(user?.id, user?.guid);

        const response = await roleService.deleteRoleUser(userId, roleId);
        if (response) {
            this.componentDidMount();
        }
    }

    render() {        
        const {loaded, pagedData, sortColumn } = this.state;

        const { role } = this.props;

        const addLink = "editRole/" + role.id + "/addUserToRole";

        return (
            <Loading loaded={loaded}>
                <Permission privilegeKey="AddRoleUser">
                <div>
                    <Button id="btnAddUserToRole" buttonType={ButtonType.primary} to={addLink}>Add</Button>
                    </div>
                </Permission>
                <hr/>
                <UserRolesTable data={pagedData} sortColumn={sortColumn} onChangePage={this.changePage} onSort={this.onSort} onSearch={this.onSearch} onDelete={this.onDelete}/>
            </Loading>
        );
    }
}

const UserRoleEditor = withRouter(UserRoleEditorNoRouter);

export default UserRoleEditor;
