<commit_before>import { Injectable } from '@angular/core';
import { Http }    from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/toPromise';

/** 
 * Class to describe the structure of a command 
 */
export class CommandObject {
  name: string;
  properties: string;
}

export class VirtualTile {
  _id: string;
  virtualName: string;
  application: string;
  tile: any;
  __v: number;
}



@Injectable()
export class TilesApi {
  defaultEventMappings = {
    btnON: {
      type: 'button_event',
      event: 'pressed'
    },
    btnOFF: {
      type: 'button_event',
      event: 'released'
    }
  };
  eventMappings = {};// {username: {tile: mappingsForTile}}
  username: string = 'TestUser';
  hostAddress: string = '172.16.58.3';//'172.16.17.32';
  mqttPort: number = 8080;
  apiPort: number = 3000;

  constructor(private http: Http,
              private storage: Storage) {
  };

  /** 
   * Returns an object with name and properties from the inputstring
   * @param {string} eventString - A string on the format eventName,properties...
   */
  getEventStringAsObject = (eventString: string): CommandObject => {
    const params = eventString.split(',');
    if (params.length > 1){
      return {
          name: params[0],
          properties: Array.prototype.slice.call(params, 1)
      };
    }
    return null;
  };

  /** 
   * Returns a string from the given commandObject
   * @param {CommansObject} cmdObj - the command to turn into a string
   */
  getCommandObjectAsString = (cmdObj: CommandObject): string => {
    return `${cmdObj.name},${cmdObj.properties.toString()}`;
  };

  /** 
   * Create a new object that has all the attributes from both inputobjects
   * @param {any} obj1 - The first object
   * @param {any} obj2 - The second object
   */
  extend = (obj1: any, obj2: any): any => {
    let extended = {};
    for (let attrname of obj1) {
      extended[attrname] = obj1[attrname];
    }
    for (let attrname of obj2) {
      if (extended[attrname] !== undefined) {
        extended[attrname] = obj2[attrname];
      } else {
        // Adds a 1 to the key if the key already exists
        extended[attrname + '1'] = obj2[attrname];
      }
    }
    return extended;
  };

  /** 
   * Tests if a device is a tile
   * @param {any} device - the device to test
   */
  isTilesDevice = (device: any): boolean => {
    return device.name != null && device.name.substring(0, 4) === 'Tile';
  };

  /** 
   * Set a username for the tile owner/user
   * @param {string} username - The new username
   */
  setUsername = (username: string): void => {
    this.username = username;
  };

  /** 
   * Set the host address
   * @param {string} hostAddress - The url/ip address of the host
   */
  setHostAddress = (hostAddress: string): void => {
    this.hostAddress = hostAddress;
  };

  /** 
   * Set the port for connecting to the server
   * @param {number} hostMqttPort - the port number 
   */
  setHostMqttPort = (hostMqttPort: number): void => {
    this.mqttPort = hostMqttPort;
  };

  /** 
   * Get all registered applications for all users
   */
  getAllApplications = (applicationId: string): void => {
    const url = `http://${this.hostAddress}:${this.apiPort}/applications`;
    this.http.get(url)
            .toPromise()
            .then(res => {
              // TODO: do something with the applications here
            })
            //.catch(err => alert('failed getting applications with error: ' + err));
  };

  /** 
   * Get the details of an application
   * @param {string} applicationId - The application ID
   */
  getApplicationDetails = (applicationId: string): Promise<any> => {
    //const url = `http://${this.hostAddress}:${this.apiPort}/applications/${applicationId}`;
    const url = `http://${this.hostAddress}:${this.apiPort}/applications/${applicationId}`;
    return this.http.get(url)
            .toPromise()
            .then(res => {
              return res.json();
            })
            .catch(err => {
              console.log('failed getting applications with error: ' + err);
              console.log('url '+url)
              return null;
            });
  };

  /** 
   * Get the tiles belonging to an application
   * @param {string} applicationId - The application ID
   */
  getApplicationTiles = (applicationId: string): Promise<any> => {
    return this.getApplicationDetails(applicationId).then(res => res.virtualTiles);
  };

  /**
   * Pair a physical tile with a virtual tile registered on the app
   * @param {string} deviceId - The physical tile
   * @param {string} virtualTileId - The virtual tile
   * @param {string} applicationId - The application the virtual tile is registered to
   */
  pairDeviceToVirualTile = (deviceId: string, virtualTileId: string, applicationId: string): void => {
    const url = `http://${this.hostAddress}:${this.apiPort}/applications/${applicationId}/${virtualTileId}`;
    const body = { tile: deviceId };
    // TODO: Device name must be updated to match the name of the virtual tile
    this.http.post(url, body).toPromise()
             .then(res => {
               // Do we even get a response? 
             })
             .catch(err => {
               alert('An error occured preventing the pairing of the physical and virtual tile');
             });
  };

  /**
   * Set the eventmapprings for a tile
   * @param {string} deviceId - The target tile
   * @param {any} - eventmappings to store for the tile
   */
  setEventMappings = (deviceId: string, eventMappings: any): void => {<commit_msg>fix the body and the headers of the pairing method in tilesApi<commit_after>import { Injectable } from '@angular/core';
import { Headers, Http }    from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/toPromise';

/** 
 * Class to describe the structure of a command 
 */
export class CommandObject {
  name: string;
  properties: string;
}

export class VirtualTile {
  _id: string;
  virtualName: string;
  application: string;
  tile: any;
  __v: number;
}



@Injectable()
export class TilesApi {
  defaultEventMappings = {
    btnON: {
      type: 'button_event',
      event: 'pressed'
    },
    btnOFF: {
      type: 'button_event',
      event: 'released'
    }
  };
  eventMappings = {};// {username: {tile: mappingsForTile}}
  username: string = 'TestUser';
  hostAddress: string = '172.16.58.3';//'172.16.17.32';
  mqttPort: number = 8080;
  apiPort: number = 3000;

  constructor(private http: Http,
              private storage: Storage) {
  };

  /** 
   * Returns an object with name and properties from the inputstring
   * @param {string} eventString - A string on the format eventName,properties...
   */
  getEventStringAsObject = (eventString: string): CommandObject => {
    const params = eventString.split(',');
    if (params.length > 1){
      return {
          name: params[0],
          properties: Array.prototype.slice.call(params, 1)
      };
    }
    return null;
  };

  /** 
   * Returns a string from the given commandObject
   * @param {CommansObject} cmdObj - the command to turn into a string
   */
  getCommandObjectAsString = (cmdObj: CommandObject): string => {
    return `${cmdObj.name},${cmdObj.properties.toString()}`;
  };

  /** 
   * Create a new object that has all the attributes from both inputobjects
   * @param {any} obj1 - The first object
   * @param {any} obj2 - The second object
   */
  extend = (obj1: any, obj2: any): any => {
    let extended = {};
    for (let attrname of obj1) {
      extended[attrname] = obj1[attrname];
    }
    for (let attrname of obj2) {
      if (extended[attrname] !== undefined) {
        extended[attrname] = obj2[attrname];
      } else {
        // Adds a 1 to the key if the key already exists
        extended[attrname + '1'] = obj2[attrname];
      }
    }
    return extended;
  };

  /** 
   * Tests if a device is a tile
   * @param {any} device - the device to test
   */
  isTilesDevice = (device: any): boolean => {
    return device.name != null && device.name.substring(0, 4) === 'Tile';
  };

  /** 
   * Set a username for the tile owner/user
   * @param {string} username - The new username
   */
  setUsername = (username: string): void => {
    this.username = username;
  };

  /** 
   * Set the host address
   * @param {string} hostAddress - The url/ip address of the host
   */
  setHostAddress = (hostAddress: string): void => {
    this.hostAddress = hostAddress;
  };

  /** 
   * Set the port for connecting to the server
   * @param {number} hostMqttPort - the port number 
   */
  setHostMqttPort = (hostMqttPort: number): void => {
    this.mqttPort = hostMqttPort;
  };

  /** 
   * Get all registered applications for all users
   */
  getAllApplications = (applicationId: string): void => {
    const url = `http://${this.hostAddress}:${this.apiPort}/applications`;
    this.http.get(url)
            .toPromise()
            .then(res => {
              // TODO: do something with the applications here
            })
            //.catch(err => alert('failed getting applications with error: ' + err));
  };

  /** 
   * Get the details of an application
   * @param {string} applicationId - The application ID
   */
  getApplicationDetails = (applicationId: string): Promise<any> => {
    //const url = `http://${this.hostAddress}:${this.apiPort}/applications/${applicationId}`;
    const url = `http://${this.hostAddress}:${this.apiPort}/applications/${applicationId}`;
    return this.http.get(url)
            .toPromise()
            .then(res => {
              return res.json();
            })
            .catch(err => {
              console.log('failed getting applications with error: ' + err);
              console.log('url '+url)
              return null;
            });
  };

  /** 
   * Get the tiles belonging to an application
   * @param {string} applicationId - The application ID
   */
  getApplicationTiles = (applicationId: string): Promise<any> => {
    return this.getApplicationDetails(applicationId).then(res => res.virtualTiles);
  };

  /**
   * Pair a physical tile with a virtual tile registered on the app
   * @param {string} deviceId - The physical tile
   * @param {string} virtualTileId - The virtual tile
   * @param {string} applicationId - The application the virtual tile is registered to
   */
  pairDeviceToVirualTile = (deviceId: string, virtualTileId: string, applicationId: string): void => {
    const url = `http://${this.hostAddress}:${this.apiPort}/applications/${applicationId}/${virtualTileId}`;
    const body = JSON.stringify({ tile: deviceId });
    const headerFields = new Headers({'Content-Type': 'application/json'});

    console.log('url: ' + url + ' body: ' + body)
    // TODO: Device name must be updated to match the name of the virtual tile
    this.http.post(url, body, {headers: headerFields}).toPromise()
             .then(res => {
               // Do we even get or need a response? 
             })
             .catch(err => {
               console.log('An error occured preventing the pairing of the physical and virtual tile');
             });
  };

  /**
   * Set the eventmapprings for a tile
   * @param {string} deviceId - The target tile
   * @param {any} - eventmappings to store for the tile
   */
  setEventMappings = (deviceId: string, eventMappings: any): void => {
{'fraction_non_alphanumeric': 0.13208209086125242, 'fraction_numerical': 0.0071917207507454835, 'mean_word_length': 2.5757290686735654, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2753252', 'n_tokens_mistral': 3433, 'n_tokens_neox': 3330, 'n_words': 1004}