import services from '../../../../constants/endpoints.json';
import { trimXML } from '../../helpers/createXMLS';
import { request } from '../../helpers/request';
import { UserDetailResponse, UserRoleAllResponse, UserUpdateResponse } from './types';

const parseString = require('react-native-xml2js').parseString;

export class UserManagementApi {
  private config = services.userManagement;

  async userRoleAllGet(skautISToken: string, userID: string) {
    const attributes = [
      { name: 'ID_Login', value: skautISToken },
      { name: 'ID_User', value: userID },
      { name: 'IsActive', value: 'true' },
    ];
    return request(this.config.name, this.config.entities.userRoleAll, attributes).then(data => {
      let res: UserRoleAllResponse[] = [];
      parseString(
        trimXML(data),
        (_err: any, result: any) =>
          (res = result.UserRoleAllResponse.UserRoleAllResult[0].UserRoleAllOutput.map(
            (item: any) => {
              const output: UserRoleAllResponse = {
                id: item.ID[0],
                idRole: item.ID_Role[0],
                idUnit: item.ID_Unit[0],
                role: item.Role[0],
                unit: item.Unit[0],
                displayName: item.DisplayName[0],
              };
              return output;
            },
          )),
      );
      return res;
    });
  }

  async userRoleUpdate(token: string, userRole: string) {
    const attributes = [
      { name: 'ID', value: token },
      { name: 'ID_UserRole', value: userRole },
    ];
    return request(this.config.name, this.config.entities.loginUpdate, attributes).then(data => {
      let res: UserUpdateResponse | undefined;
      parseString(trimXML(data), (_err: any, result: any) => {
        res = {
          idUnit: result.LoginUpdateResponse.LoginUpdateResult[0].ID_Unit[0],
          idRole: userRole,
        };
      });
      return res;
    });
  }

  async userDetailGet(token: string, userId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: userId },
    ];
    return request(this.config.name, this.config.entities.userDetail, attributes).then(data => {
      let res: UserDetailResponse | undefined;
      parseString(trimXML(data), (_err: any, result: any) => {
        const item = result.UserDetailResponse.UserDetailResult[0];
        res = {
          personId: item.ID_Person[0],
          personDisplayName: item.Person[0],
        };
      });
      return res;
    });
  }
}
