import services from '../../../../constants/endpoints.json';
import { trimXML } from '../../helpers/createXMLS';
import { getParam, request } from '../../helpers/request';
import { MessageDetailResponse, MessageItemResponse } from './types';

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

export class MessageAPI {
  private config = services.message;

  async messageAllGet(skautISToken: string) {
    const attributes = [
      { name: 'ID_Login', value: skautISToken },
      { name: 'IsActive', value: 'true' },
    ];
    return request(this.config.name, this.config.entities.messageAllWeb, attributes).then(data => {
      let res: MessageItemResponse[] = [];
      parseString(trimXML(data), (_err: any, result: any) => {
        if (result.MessageAllWebResponse.MessageAllWebResult[0] === '') return [];
        res = result.MessageAllWebResponse.MessageAllWebResult[0].MessageAllWebOutput.map(
          (item: any) => {
            const output: MessageItemResponse = {
              id: getParam(item, 'ID'),
              group: getParam(item, 'MessageGroup'),
              created: new Date(getParam(item, 'DateCreate')),
              header: getParam(item, 'DisplayName'),
              isRead: getParam(item, 'IsRead') === 'true',
            };
            return output;
          },
        );
      });
      return res;
    });
  }

  async messageDetailGet(token: string, messageId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: messageId },
    ];
    return request(this.config.name, this.config.entities.messageDetail, attributes).then(data => {
      let res: MessageDetailResponse | undefined;
      parseString(trimXML(data), (_err: any, result: any) => {
        const item = result.MessageDetailResponse.MessageDetailResult[0];
        res = {
          group: getParam(item, 'MessageGroup'),
          created: new Date(getParam(item, 'DateCreate')),
          header: getParam(item, 'DisplayName'),
          isHTML: getParam(item, 'IsHtml') === 'true',
          body: getParam(item, 'Body'),
        };
      });
      return res;
    });
  }

  async messageDelete(token: string, messageId: string) {
    const attributes = [
      { name: 'ID_Login', value: token },
      { name: 'ID', value: messageId },
      { name: 'Delete', value: 'true' },
    ];
    return request(this.config.name, this.config.entities.messageUpdateDelete, attributes).then(
      () => {},
    );
  }
}
