import services from '../../../../constants/endpoints.json';
import { getTimeAsString, getTimeFromString } from '../../../../helpers/stringHelpers';
import { trimXML } from '../../helpers/createXMLS';
import { getParam, request } from '../../helpers/request';
import {
  FunctionAllPersonResponse,
  FunctionAllResponse,
  MembershipAllPersonResponse,
  MembershipAllResponse,
  OfferAllResponse,
  PersonContactAllResponse,
  PersonDetailResponse,
  PersonOtherDetailResponse,
  PersonPhotoResponse,
  QualificationAllResponse,
  UnitRegistrationAllResponse,
  UnitContactAllResponse,
  UnitDetailResponse,
  UnitTreeAllResponse,
  UnitRegistrationMembersUnit,
  UnitRegistrationMembersCategory,
  AdvertisingDetailResponse,
  AdvertisingCategoryAllResponse,
  MeetingDateAllResponse,
  OccupationAllUnitResponse,
  RealtyAllResponse,
  MeetingDateDetailResponse,
  AdvertisingCategoryDetailResponse,
  MembershipApplicationInsertResponse,
  OfferTypeAllResponse,
  PersonAllResponse,
  PersonAllCatalogResponse,
  UnitAllResponse,
  PersonAllEventCampMultiResponse,
  UnitAllCampResponse,
} from './types';

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

export class OrganizationUnitApi {
  private config = services.organizationUnit;

  async personPhotoGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: personId },
      { name: 'Size', value: 'normal' },
    ];
    return request(this.config.name, this.config.entities.personPhoto, attributes).then(data => {
      let res: PersonPhotoResponse | undefined;
      parseString(trimXML(data), (_err: any, result: any) => {
        const item = result.PersonPhotoResponse.PersonPhotoResult[0];
        res = {
          id: personId,
          photoContent: getParam(item, 'PhotoContent'),
        };
      });
      return res;
    });
  }

  async personDetailGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: personId },
    ];
    return request(this.config.name, this.config.entities.personDetail, attributes)
      .then(data => {
        let res: PersonDetailResponse | undefined;
        parseString(trimXML(data), (_err: any, result: any) => {
          const item = result.PersonDetailResponse.PersonDetailResult[0];
          res = {
            id: getParam(item, 'ID'),
            firstName: getParam(item, 'FirstName'),
            lastName: getParam(item, 'LastName'),
            nickName: getParam(item, 'NickName'),
            displayName: getParam(item, 'DisplayName'),
            identificationCode: getParam(item, 'IdentificationCode'),
            birthday: getParam(item, 'Birthday'),
            sex: getParam(item, 'Sex'),
            street: getParam(item, 'Street'),
            city: getParam(item, 'City'),
            postcode: getParam(item, 'Postcode'),
            state: getParam(item, 'State'),
            identificationCodeHasPermission:
              getParam(item, 'IdentificationCodeHasPermission') === 'true',
            displayAddress: getParam(item, 'displayAdress') === 'true',
            displayBirthday: getParam(item, 'DisplayBirthday') === 'true',
            displayFunction: getParam(item, 'DisplayFunction') === 'true',
            displayMembership: getParam(item, 'DisplayMembership') === 'true',
            displayOffer: getParam(item, 'DisplayOffer') === 'true',
            displayQualification: getParam(item, 'DisplayQualification') === 'true',
          };
        });
        return res;
      })
      .catch(err => {
        return err;
      });
  }

  async personOtherDetailGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: personId },
    ];
    return request(this.config.name, this.config.entities.personOtherDetail, attributes).then(
      data => {
        let res: PersonOtherDetailResponse | undefined;
        parseString(trimXML(data), (_err: any, result: any) => {
          const item = result.PersonOtherDetailResponse.PersonOtherDetailResult[0];
          res = {
            assurance: getParam(item, 'Assurance'),
            insuranceNumber: getParam(item, 'InsuranceNumber'),
            allergy: getParam(item, 'Allergy'),
            drugs: getParam(item, 'Drugs'),
            healthLimitation: getParam(item, 'HealthLimitation'),
            note: getParam(item, 'Note'),
          };
        });
        return res;
      },
    );
  }

  async personContactAllGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Person', value: personId },
    ];
    return request(this.config.name, this.config.entities.personContactAll, attributes).then(
      data => {
        let res: PersonContactAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.PersonContactAllResponse.PersonContactAllResult[0] === '') return [];
          res =
            result.PersonContactAllResponse.PersonContactAllResult[0].PersonContactAllOutput.map(
              (item: any) => {
                const output: PersonContactAllResponse = {
                  contactType: getParam(item, 'ContactType'),
                  contactTypeId: getParam(item, 'ID_ContactType'),
                  value: getParam(item, 'Value'),
                  displayValue: getParam(item, 'DisplayValue'),
                };
                return output;
              },
            );
        });

        return res;
      },
    );
  }

  async functionPersonAllGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Person', value: personId },
    ];

    return request(this.config.name, this.config.entities.functionAllPerson, attributes)
      .then(data => {
        let res: FunctionAllPersonResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.FunctionAllPersonResponse.FunctionAllPersonResult[0] === '') return [];
          res = result.FunctionAllPersonResponse.FunctionAllPersonResult[0].FunctionAllOutput?.map(
            (item: any) => {
              const output: FunctionAllPersonResponse = {
                unit: getParam(item, 'Unit'),
                function: getParam(item, 'FunctionType'),
              };
              return output;
            },
          );
        });
        return res;
      })
      .catch(() => {
        return [];
      });
  }

  async qualificationAllGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Person', value: personId },
    ];

    return request(this.config.name, this.config.entities.qualificationAll, attributes)
      .then(data => {
        let res: QualificationAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.QualificationAllResponse.QualificationAllResult[0] === '') return [];
          res =
            result.QualificationAllResponse.QualificationAllResult[0].QualificationAllOutput?.map(
              (item: any) => {
                const output: QualificationAllResponse = {
                  qualificationType: getParam(item, 'QualificationType'),
                };
                return output;
              },
            );
        });
        return res;
      })
      .catch(() => {
        return [];
      });
  }

  async offerAllGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Person', value: personId },
    ];

    return request(this.config.name, this.config.entities.offerAll, attributes)
      .then(data => {
        let res: OfferAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.OfferAllResponse.OfferAllResult[0] === '') return [];
          res = result.OfferAllResponse.OfferAllResult[0].OfferAllOutput?.map((item: any) => {
            const output: OfferAllResponse = {
              offerType: getParam(item, 'OfferType'),
            };
            return output;
          });
        });
        return res;
      })
      .catch(() => {
        return [];
      });
  }

  async membershipAllGet(token: string, personId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Person', value: personId },
    ];

    return request(this.config.name, this.config.entities.membershipAllPerson, attributes)
      .then(data => {
        let res: MembershipAllPersonResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.MembershipAllPersonResponse.MembershipAllPersonResult[0] === '') return [];
          res =
            result.MembershipAllPersonResponse.MembershipAllPersonResult[0].MembershipAllOutput?.map(
              (item: any) => {
                const output: MembershipAllPersonResponse = {
                  unit: getParam(item, 'Unit'),
                  unitId: getParam(item, 'ID_Unit'),
                  membershipTypeId: getParam(item, 'ID_MembershipType'),
                  membershipType: getParam(item, 'MembershipType'),
                };
                return output;
              },
            );
        });
        return res;
      })
      .catch(() => {
        return [];
      });
  }

  async unitDetailGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: unitId },
    ];
    return request(this.config.name, this.config.entities.unitDetail, attributes).then(data => {
      let res: UnitDetailResponse | undefined;
      parseString(trimXML(data), (_err: any, result: any) => {
        const item = result.UnitDetailResponse.UnitDetailResult[0];
        res = {
          id: getParam(item, 'ID'),
          displayName: getParam(item, 'DisplayName'),
          city: getParam(item, 'City'),
          street: getParam(item, 'Street'),
          postcode: getParam(item, 'Postcode'),
          postalCity: getParam(item, 'PostalCity'),
          postalStreet: getParam(item, 'PostalStreet'),
          postalPostcode: getParam(item, 'PostalPostcode'),
          postalFirstLine: getParam(item, 'PostalFirstLine'),
          parentUnitId: getParam(item, 'ID_UnitParent'),
          regNumber: getParam(item, 'RegistrationNumber'),
        };
      });
      return res;
    });
  }

  async unitTreeAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_UnitParent', value: unitId },
    ];
    return request(this.config.name, this.config.entities.unitTreeAll, attributes).then(data => {
      let res: UnitTreeAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.UnitTreeAllResponse.UnitTreeAllResult[0] === '') return [];
        res = result.UnitTreeAllResponse.UnitTreeAllResult[0].UnitTreeAllOutput?.map(
          (item: any) => {
            const output: UnitTreeAllResponse = {
              id: getParam(item, 'ID_Unit'),
              unit: getParam(item, 'Unit'),
              registrationNumber: getParam(item, 'RegistrationNumber'),
            };
            return output;
          },
        );
      });
      return res;
    });
  }

  async unitContactAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.unitContactAll, attributes).then(data => {
      let res: UnitContactAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.UnitContactAllResponse.UnitContactAllResult[0] === '') return [];
        res = result.UnitContactAllResponse.UnitContactAllResult[0].UnitContactAllOutput?.map(
          (item: any) => {
            const output: UnitContactAllResponse = {
              contactType: getParam(item, 'ContactType'),
              contactTypeId: getParam(item, 'ID_ContactType'),
              value: getParam(item, 'Value'),
              displayValue: getParam(item, 'DisplayValue'),
            };
            return output;
          },
        );
      });
      return res;
    });
  }

  async unitFunctionAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.functionAll, attributes).then(data => {
      let res: FunctionAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.FunctionAllResponse.FunctionAllResult[0] === '') return [];
        res = result.FunctionAllResponse.FunctionAllResult[0].FunctionAllOutput?.map(
          (item: any) => {
            const output: FunctionAllResponse = {
              id: getParam(item, 'ID_Person'),
              person: getParam(item, 'Person'),
              functionType: getParam(item, 'FunctionType'),
              functionTypeId: getParam(item, 'ID_FunctionType'),
            };
            return output;
          },
        );
      });
      return res;
    });
  }

  async unitMembershipAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.membershipAll, attributes)
      .then(data => {
        let res: MembershipAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.MembershipAllResponse.MembershipAllResult[0] === '') return [];
          res = result.MembershipAllResponse.MembershipAllResult[0].MembershipAllOutput?.map(
            (item: any) => {
              const output: MembershipAllResponse = {
                person: getParam(item, 'Person'),
                personId: getParam(item, 'ID_Person'),
                unit: getParam(item, 'Unit'),
                category: getParam(item, 'MembershipCategory'),
              };
              return output;
            },
          );
        });
        return res;
      })
      .catch(err => {
        return [err];
      });
  }

  async unitRegistrationsAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.unitRegistrationAll, attributes)
      .then(data => {
        let res: UnitRegistrationAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.UnitRegistrationAllResponse.UnitRegistrationAllResult[0] === '') return [];
          res =
            result.UnitRegistrationAllResponse.UnitRegistrationAllResult[0].UnitRegistrationAllOutput?.map(
              (item: any) => {
                const output: UnitRegistrationAllResponse = {
                  id: getParam(item, 'ID'),
                  unit: getParam(item, 'Unit'),
                  year: getParam(item, 'Year'),
                  displayName: getParam(item, 'DisplayName'),
                  isAccepted: getParam(item, 'IsAccepted') === 'true',
                  isDelivered: getParam(item, 'IsDelivered') === 'true',
                };
                return output;
              },
            );
        });
        return res;
      })
      .catch(err => {
        return [err];
      });
  }

  async unitRegistrationMembersGet(token: string, yearId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: yearId },
    ];
    return request(this.config.name, this.config.entities.unitRegistrationMembers, attributes).then(
      data => {
        let units: UnitRegistrationMembersUnit[] = [];
        let ages: UnitRegistrationMembersCategory[] = [];
        let restrictions: UnitRegistrationMembersCategory[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          const parentBody =
            result.UnitRegistrationMembersResponse.UnitRegistrationMembersResult[0];
          if (parentBody === '') return [];
          if (parentBody.Units[0] !== '') {
            units = parentBody.Units[0].UnitRegistrationMembersUnits.map((item: any) => {
              const output: UnitRegistrationMembersUnit = {
                type: getParam(item, 'UnitType'),
                count: Number(getParam(item, 'Count')),
              };
              return output;
            });
          }
          if (parentBody.MembersAge[0] !== '') {
            ages = parentBody.MembersAge[0].UnitRegistrationMembersAge.map((item: any) => {
              const output: UnitRegistrationMembersCategory = {
                displayName: getParam(item, 'DisplayName'),
                category: getParam(item, 'AgeCategory'),
                type: getParam(item, 'ID_MembershipType'),
                row: getParam(item, 'Row'),
                count: Number(getParam(item, 'Count')),
              };
              return output;
            });
          }
          if (parentBody.MembersCategory[0] !== '') {
            restrictions = parentBody.MembersCategory[0].UnitRegistrationMembersCategory.map(
              (item: any) => {
                const output: UnitRegistrationMembersCategory = {
                  displayName: getParam(item, 'DisplayName'),
                  category: getParam(item, 'MembershipCategory'),
                  type: getParam(item, 'ID_MembershipType'),
                  row: getParam(item, 'Row'),
                  count: Number(getParam(item, 'Count')),
                };
                return output;
              },
            );
          }
        });
        return {
          units,
          ages,
          restrictions,
        };
      },
    );
  }

  async unitAdvertisingDetailGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.advertisingDetail, attributes)
      .then(data => {
        let res: AdvertisingDetailResponse | undefined;
        parseString(trimXML(data), (_err: any, result: any) => {
          const item = result.AdvertisingDetailResponse.AdvertisingDetailResult[0];
          res = {
            unit: getParam(item, 'Unit'),
            note: getParam(item, 'Note'),
          };
        });
        return res;
      })
      .catch(err => {
        return err;
      });
  }

  async unitAdvertisingDetailUpdate(token: string, unitId: string, note: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
      { name: 'Note', value: note },
    ];
    return request(this.config.name, this.config.entities.advertisingUpdate, attributes).then(
      () => {},
    );
  }

  async unitAdvertisingCategoryAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.advertisingCategoryAll, attributes)
      .then(data => {
        let res: AdvertisingCategoryAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.AdvertisingCategoryAllResponse.AdvertisingCategoryAllResult[0] === '')
            return [];
          res =
            result.AdvertisingCategoryAllResponse.AdvertisingCategoryAllResult[0].AdvertisingCategoryAllOutput?.map(
              (item: any) => {
                const output: AdvertisingCategoryAllResponse = {
                  id: getParam(item, 'ID'),
                  sex: getParam(item, 'Sex'),
                  meetingDate: getParam(item, 'MeetingDate'),
                };
                return output;
              },
            );
        });
        return res;
      })
      .catch(err => {
        return err;
      });
  }

  async unitMeetingDateAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.meetingDateAll, attributes).then(data => {
      let res: MeetingDateAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.MeetingDateAllResponse.MeetingDateAllResult[0] === '') return [];
        res = result.MeetingDateAllResponse.MeetingDateAllResult[0].MeetingDateAllOutput?.map(
          (item: any) => {
            const output: MeetingDateAllResponse = {
              id: getParam(item, 'ID'),
              displayName: getParam(item, 'DisplayName'),
            };
            return output;
          },
        );
      });
      return res;
    });
  }

  async unitOccupationAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.occupationAllUnit, attributes).then(
      data => {
        let res: OccupationAllUnitResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.OccupationAllUnitResponse.OccupationAllUnitResult[0] === '') return [];
          res =
            result.OccupationAllUnitResponse.OccupationAllUnitResult[0].OccupationAllUnitOutput?.map(
              (item: any) => {
                const output: OccupationAllUnitResponse = {
                  id: getParam(item, 'ID'),
                  realtyId: getParam(item, 'ID_Realty'),
                  realtyType: getParam(item, 'RealtyType'),
                };
                return output;
              },
            );
        });
        return res;
      },
    );
  }

  async unitRealtyAllGet(token: string, unitId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
    ];
    return request(this.config.name, this.config.entities.realtyAll, attributes).then(data => {
      let res: RealtyAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.RealtyAllResponse.RealtyAllResult[0] === '') return [];
        res = result.RealtyAllResponse.RealtyAllResult[0].RealtyAllOutput?.map((item: any) => {
          const output: RealtyAllResponse = {
            id: getParam(item, 'ID'),
            displayName: getParam(item, 'DisplayName'),
          };
          return output;
        });
      });
      return res;
    });
  }

  async unitMeetingDateGet(token: string, dateId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: dateId },
    ];
    return request(this.config.name, this.config.entities.meetingDateDetail, attributes).then(
      data => {
        let res: MeetingDateDetailResponse | undefined;
        parseString(trimXML(data), (_err: any, result: any) => {
          const item = result.MeetingDateDetailResponse.MeetingDateDetailResult[0];
          res = {
            weekDayId: getParam(item, 'ID_WeekDay'),
            weekDay: getParam(item, 'WeekDay'),
            timeFrom: getTimeFromString(getParam(item, 'TimeFrom')),
            timeTo: getTimeFromString(getParam(item, 'TimeTo')),
            periodicity: getParam(item, 'Periodicity'),
            occupationId: getParam(item, 'ID_Occupation'),
          };
        });
        return res;
      },
    );
  }

  async unitMeetingDateAdd(
    token: string,
    unitId: string,
    payload: MeetingDateDetailResponse,
    dateId?: string,
  ) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
      { name: 'ID_WeekDay', value: payload.weekDayId },
      { name: 'WeekDay', value: payload.weekDay },
      { name: 'TimeFrom', value: getTimeAsString(payload.timeFrom) },
      { name: 'TimeTo', value: getTimeAsString(payload.timeTo) },
      { name: 'Periodicity', value: payload.periodicity },
    ];
    if (payload.occupationId.length) {
      attributes.push({ name: 'ID_Occupation', value: payload.occupationId });
    }
    if (dateId) {
      attributes.push({ name: 'ID', value: dateId });
    }
    return request(
      this.config.name,
      dateId ? this.config.entities.meetingDateUpdate : this.config.entities.meetingDateInsert,
      attributes,
    ).then(() => {});
  }

  async unitMeetingDateDelete(token: string, dateId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: dateId },
    ];
    return request(this.config.name, this.config.entities.meetingDateDelete, attributes).then(
      () => {},
    );
  }

  async unitAdvertisingCategoryGet(token: string, categoryId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: categoryId },
    ];
    return request(
      this.config.name,
      this.config.entities.advertisingCategoryDetail,
      attributes,
    ).then(data => {
      let res: AdvertisingCategoryDetailResponse | undefined;
      parseString(trimXML(data), (_err: any, result: any) => {
        const item = result.AdvertisingCategoryDetailResponse.AdvertisingCategoryDetailResult[0];
        res = {
          ageFrom: getParam(item, 'AgeFrom'),
          ageTo: getParam(item, 'AgeTo'),
          sex: getParam(item, 'Sex'),
          sexId: getParam(item, 'ID_Sex'),
          meetingDateId: getParam(item, 'ID_MeetingDate'),
          note: getParam(item, 'Note'),
        };
      });
      return res;
    });
  }

  async unitAdvertisingCategoryAdd(
    token: string,
    unitId: string,
    payload: AdvertisingCategoryDetailResponse,
    categoryId?: string,
  ) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
      { name: 'ID_Sex', value: payload.sexId },
      { name: 'Sex', value: payload.sex },
      { name: 'AgeFrom', value: payload.ageFrom },
      { name: 'AgeTo', value: payload.ageTo },
      { name: 'ID_MeetingDate', value: payload.meetingDateId },
      { name: 'Note', value: payload.note },
    ];
    if (categoryId) {
      attributes.push({ name: 'ID', value: categoryId });
    }
    return request(
      this.config.name,
      categoryId
        ? this.config.entities.advertisingCategoryUpdate
        : this.config.entities.advertisingCategoryInsert,
      attributes,
    ).then(() => {});
  }

  async unitAdvertisingCategoryDelete(token: string, categoryId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: categoryId },
    ];
    return request(
      this.config.name,
      this.config.entities.advertisingCategoryDelete,
      attributes,
    ).then(() => {});
  }

  async unitApplicationInsert(
    token: string,
    unitId: string,
    payload: MembershipApplicationInsertResponse,
  ) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_Unit', value: unitId },
      { name: 'FirstName', value: payload.name },
      { name: 'LastName', value: payload.surname },
      { name: 'FirstNameParent', value: payload.parentName },
      { name: 'LastNameParent', value: payload.parentSurname },
      { name: 'Email', value: payload.email },
      { name: 'IsAdult', value: `${!payload.isYounger}` },
    ];
    return request(
      this.config.name,
      this.config.entities.membershipApplicationInsert,
      attributes,
    ).then(() => {});
  }

  async offerTypesAllGet(token: string) {
    const attributes = [{ name: 'ID_Login', value: token }];
    return request(this.config.name, this.config.entities.offerTypeAll, attributes)
      .then(data => {
        let res: OfferTypeAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.OfferTypeAllResponse.OfferTypeAllResult[0] === '') return [];
          res = result.OfferTypeAllResponse.OfferTypeAllResult[0].OfferTypeAllOutput?.map(
            (item: any) => {
              const output: OfferTypeAllResponse = {
                id: getParam(item, 'ID'),
                displayName: getParam(item, 'DisplayName'),
              };
              return output;
            },
          );
        });
        return res;
      })
      .catch(err => {
        return [err];
      });
  }

  async personAllGet(token: string, name?: string, regNumber?: string, regNumberStart?: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      ...(name ? [{ name: 'DisplayName', value: name }] : []),
      ...(regNumber ? [{ name: 'IdentificationCode', value: regNumber }] : []),
      ...(regNumberStart ? [{ name: 'IdentificationCodeStartsWith', value: regNumberStart }] : []),
    ];
    return request(this.config.name, this.config.entities.personAll, attributes).then(data => {
      let res: PersonAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.PersonAllResponse.PersonAllResult[0] === '') return [];
        res = result.PersonAllResponse.PersonAllResult[0].PersonAllOutput?.map((item: any) => {
          const output: PersonAllResponse = {
            id: getParam(item, 'ID'),
            displayName: getParam(item, 'DisplayName'),
          };
          return output;
        });
      });
      return res;
    });
  }

  async PersonAllCatalogGet(
    token: string,
    name?: string,
    regNumber?: string,
    regNumberStart?: string,
    typeId?: string,
  ) {
    const attributes = [
      { name: 'ID_Login', value: token },
      ...(name ? [{ name: 'Name', value: name }] : []),
      ...(regNumber ? [{ name: 'IdentificationCode', value: regNumber }] : []),
      ...(regNumberStart ? [{ name: 'IdentificationCodeStartsWith', value: regNumberStart }] : []),
      ...(typeId ? [{ name: 'ID_OfferType', value: typeId }] : []),
    ];
    return request(this.config.name, this.config.entities.personAllCatalog, attributes).then(
      data => {
        let res: PersonAllCatalogResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.PersonAllCatalogResponse.PersonAllCatalogResult[0] === '') return [];
          res =
            result.PersonAllCatalogResponse.PersonAllCatalogResult[0].PersonAllCatalogOutput?.map(
              (item: any) => {
                const output: PersonAllCatalogResponse = {
                  id: getParam(item, 'ID'),
                  displayName: getParam(item, 'DisplayName'),
                };
                return output;
              },
            );
        });
        return res;
      },
    );
  }

  async unitAllGet(
    token: string,
    number: string,
    byNumberStart: boolean,
    name: string,
    place: string,
    areaId: string,
    bankNumber: string,
    ic: string,
  ) {
    const attributes = [
      { name: 'ID_Login', value: token },
      ...(number.length ? [{ name: 'RegistrationNumber', value: number }] : []),
      { name: 'RegistrationNumberStartWith', value: `${byNumberStart}` },
      ...(name.length ? [{ name: 'DisplayName', value: name }] : []),
      ...(place.length ? [{ name: 'Location', value: place }] : []),
      ...(areaId.length ? [{ name: 'ID_AlignmentType', value: areaId }] : []),
      ...(bankNumber.length ? [{ name: 'AccountNumber', value: bankNumber }] : []),
      ...(ic.length ? [{ name: 'IC', value: ic }] : []),
    ];
    return request(this.config.name, this.config.entities.unitAll, attributes).then(data => {
      let res: UnitAllResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.UnitAllResponse.UnitAllResult[0] === '') return [];
        res = result.UnitAllResponse.UnitAllResult[0].UnitAllOutput?.map((item: any) => {
          const output: UnitAllResponse = {
            id: getParam(item, 'ID'),
            displayName: getParam(item, 'DisplayName'),
            number: getParam(item, 'RegistrationNumber'),
            place: getParam(item, 'Location'),
            type: getParam(item, 'UnitType'),
          };
          return output;
        });
      });
      return res;
    });
  }

  async personAllEventCampMultiGet(token: string, campId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID_EventCamp', value: campId },
    ];
    return request(this.config.name, this.config.entities.personAllEventCampMulti, attributes).then(
      data => {
        let res: PersonAllEventCampMultiResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.PersonAllEventCampMultiResponse.PersonAllEventCampMultiResult[0] === '')
            return [];
          res =
            result.PersonAllEventCampMultiResponse.PersonAllEventCampMultiResult[0].PersonAllEventCampMultiOutput?.map(
              (item: any) => {
                const output: PersonAllEventCampMultiResponse = {
                  id: getParam(item, 'ID'),
                  displayName: getParam(item, 'DisplayName'),
                  category: getParam(item, 'MembershipCategory'),
                  isParticipant: getParam(item, 'IsParticipant') === 'true',
                };
                return output;
              },
            );
        });
        return res;
      },
    );
  }

  async unitAllCampGet(token: string) {
    const attributes = [{ name: 'ID_Login', value: token }];
    return request(this.config.name, this.config.entities.unitAllCamp, attributes)
      .then(data => {
        let res: UnitAllCampResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.UnitAllCampResponse.UnitAllCampResult[0] === '') return [];
          res = result.UnitAllCampResponse.UnitAllCampResult[0].UnitAllCampOutput?.map(
            (item: any) => {
              const output: UnitAllCampResponse = {
                id: getParam(item, 'ID'),
                sortName: getParam(item, 'SortName'),
              };
              return output;
            },
          );
        });
        return res;
      })
      .catch(err => {
        return [err];
      });
  }
}
