import services from '../../../../constants/endpoints.json';
import { trimXML } from '../../helpers/createXMLS';
import { getByAttribute, getParam, request } from '../../helpers/request';
import { ExportPersonAllResponse, ExportPersonViewResponse } from './type';

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

export class SummaryAPI {
  private config = services.summary;

  async exportPersonAllGet(token: string) {
    const attributes = [{ name: 'ID_Login', value: token }];
    return request(this.config.name, this.config.entities.exportPersonAll, attributes).then(
      data => {
        let res: ExportPersonAllResponse[] = [];
        parseString(trimXML(data), (_err: any, result: any) => {
          if (result.ExportPersonAllResponse.ExportPersonAllResult[0] === '') return [];
          res = result.ExportPersonAllResponse.ExportPersonAllResult[0].ExportPersonAllOutput.map(
            (item: any) => {
              const output: ExportPersonAllResponse = {
                id: getParam(item, 'ID'),
                listName: getParam(item, 'ListName'),
              };
              return output;
            },
          );
        });
        return res;
      },
    );
  }

  async exportPersonViewGet(token: string, exportId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: exportId },
    ];
    return request(this.config.name, this.config.entities.exportPersonView, attributes).then(
      data => {
        const res: ExportPersonViewResponse = {};
        parseString(trimXML(data), (_err: any, result: any) => {
          const item = result.ExportPersonViewResponse.ExportPersonViewResult[0];
          const data = getParam(item, 'Data');
          const email = 'Contact_email_hlavni';
          const phone = 'Contact_telefon_hlavni';
          const name = 'DisplayName';
          const personName = 'Person';
          parseString(data, (_err: any, r: any) => {
            r?.persons.row.forEach((person: any) => {
              if (person.ID) {
                const newEmail = getByAttribute(person, email);
                const newPhone = getByAttribute(person, phone);
                const newName = getByAttribute(person, name) || getByAttribute(person, personName);
                if (newEmail) {
                  res[person.ID] = {
                    ...res[person.ID],
                    email: newEmail,
                  };
                }
                if (newPhone) {
                  res[person.ID] = {
                    ...res[person.ID],
                    phone: newPhone.replace(/(\d{3})/g, '$1 ').trim(),
                  };
                }
                if (newName) {
                  res[person.ID] = {
                    ...res[person.ID],
                    name: newName,
                  };
                }
              }
            });
          });
        });
        return res;
      },
    );
  }
}
