const xapi = require('xapi');

/* 
 * ********************************
 * EDIT THIS SECTION BELOW 
 * ********************************
 */

/* 
 * 1. Enter room identifier, e.g. room@company.com where Cisco equipment is mounted
 * You can find it in the Joan Portal
 * https://portal.getjoan.com/manage/resources/
 */
const ROOM_ID = ""

/* 2. Generate a new API Token at https://portal.getjoan.com/settings/integrations/
 * Tokens are needed for authentication between Joan Portal and Cisco equipment
 * Authentication is oauth2 based with client credentials flow
 * a.) Client ID
 */
const JOAN_CLIENT_ID = "";
/* 
 * b.) Secret
 */
const JOAN_CLIENT_SECRET = "";

/* 3. Set the thresholds. They define how much time it needs to pass before a room is booked or released
 * Tip: For huddle spaces those numbers are usually smaller, while for bigger boardrooms we recommend larger thresholds
 */
const MIN_BEFORE_BOOK = 1; // in minutes
const MIN_BEFORE_RELEASE = 1; // in minutes

/* 4. You can enable presence detection that is based from ultrasound sensor on the Cisco device. 
 * Tip: Detection via ultrasound can be useful when lighting conditions are not perfect for
 * image recognition. Downside is that it can be quite sensitive and can cause false positive
 * detections. It's best to test it and see if it works for your office environment
 */
const USE_ULTRASOUND = false;

/* 
 * *********************************
 * *********************************
 * *********************************
 *  DO NOT CHANGE BELOW THIS LINE 
 * *********************************
 * *********************************
 * *********************************
 */

const POOL_INTERVAL_IN_SEC = 10 // how often Cisco equipment is polled for the presence information in seconds
// regexs for sw version detection
const SW_REGEX = /[0-9]+.[0-9]+.[0-9]+/g;
const SW_MIN = [9, 12, 0];
// base URL for the Joan API calls
const PORTAL_BASE_URL = "https://portal.getjoan.com";


class PresenceDetector {
   /* 
    * Presence detector class handling all the logic
    * to detect presence on Cisco equipment 
    */
    constructor() {
        this._data = {
            peopleCount: 0,
            peoplePresence: false,
            inCall: false,
        };
        // flags for full/empty room timers
        this._lastFullTimer = 0;
        this._lastEmptyTimer = 0;
        this._roomIsFull = false;
        this._roomIsEmpty = false;
    
        // flag is set when we're ready to send the API call
        // after the thresholds are met
        this._sendAPI = false;
    }

    get shouldSendAPI() {
      /* 
       * Getter to get the information if thresholds were met
       * and we need to make a call on the API endpoint to process
       * presence
       */
      return this._sendAPI;
    }

    get presenceData(){
      /* 
       * Getter to get the all the presence data:
       * 1. Number of people detected
       * 2. Flag if people detected through ultrasound (if enabled), 
       * 3. Flag if somebody in call
       */
      return this._data;
    }

    apiSent() {
      /* 
       * Set the flag that the API call was sent
       */
      this._sendAPI = false;
    }

    async enableDetector() {
        /*
         * Enabling detection on Cisco equipment
         */
        console.log("Enabling presence detection...");
        if(!USE_ULTRASOUND) {
          console.log("Ultrasound detection disabled!");
        }
        xapi.config.set('HttpClient Mode', 'On');
        xapi.config.set('RoomAnalytics PeopleCountOutOfCall', 'On');
        xapi.config.set('RoomAnalytics PeoplePresenceDetector', 'On');
        console.log("Success, presence detection enabled");
    }

    _getData(command) {
        return xapi.status.get(command).catch((error) => {
            console.warning("Couldn't run the command:", command, " Error: ", error);
            return -1
        })
    }

    _isRoomOccupied() {
        /*
         * Logic that returns a boolean if room is occupied
         * combining all types of enabled presence detection
         */
        console.log(
          "# of people:"+this._data.peopleCount+
          "| Ultrasound presence detected: "+this._data.peoplePresence+
          "| Call in progress: "+this._data.inCall
        );
        return this._data.peopleCount || (USE_ULTRASOUND && this._data.peoplePresence) || this._data.inCall;
    }

    _processPresence() {
        /* 
         *  Logic for the presence information gathered from 
         *  the Cisco equipment.
         */
        if (this._isRoomOccupied()) {
            if (this._lastFullTimer == 0) {
                console.log("Room occupancy detected - starting timer...");
                this._lastFullTimer = Date.now();
                this._lastEmptyTimer = 0;
            }
            else if (Date.now() > (this._lastFullTimer + MIN_BEFORE_BOOK * 60000)) {
                this._roomIsFull = true;
                this._roomIsEmpty = false;
                this._lastFullTimer = Date.now();
                this._sendAPI = true;
                console.log("Should update room status - occupied");
            }
        }
        else {
            if (this._lastEmptyTimer == 0) {
                console.log("Room empty detected - starting timer...");
                this._lastEmptyTimer = Date.now();
                this._lastFullTimer = 0;
            }
            else if (Date.now() > (this._lastEmptyTimer + MIN_BEFORE_RELEASE * 60000) && !this._roomIsEmpty) {
                this._roomIsFull = false;
                this._roomIsEmpty = true;
                this._sendAPI = true;
                console.log("Should update room status - empty");
            }
        }
    }

    async updatePresence() {
        /* 
         * Polling the Cisco information
         * and getting presence information
         */
        const callsData = this._getData('SystemUnit State NumberOfActiveCalls');
        const presenceData = this._getData('RoomAnalytics PeoplePresence');
        const peopleCountData = this._getData('RoomAnalytics PeopleCount Current');
        
        Promise.all([callsData, presenceData, peopleCountData]).then(results => {
            const numCalls = parseInt(results[0]);
            const presence = results[1] === 'Yes' ? true:false;
            const peopleCount = parseInt(results[2]);

            this._data.peopleCount = peopleCount === -1 ? 0 : peopleCount;
            this._data.peoplePresence = presence;

            if(!USE_ULTRASOUND){
              // if ultrasound is disabled we set people presence 
              // based only of image reconigition
              this._data.peoplePresence = this._data.peopleCount ? true : false;
            }

            // process conference calls
            if (numCalls > 0) {
                this._data.inCall = true;
                this._data.peoplePresence = true; // if in call we set that people are present
            } else {
                this._data.inCall = false;
            }

            console.log("Starting to process presence data...")
            this._processPresence();
            console.log("Processing of data finished...")
        });
    }
}


class JoanAPI {
   /* 
    * Class handles everyting Joan API related
    * 
    */
    constructor() {
        if(!JOAN_CLIENT_ID || !JOAN_CLIENT_SECRET) {
          console.error(
            "Can not connect to Joan! " +
            "No client id and secret defined. You can create them at: https://portal.getjoan.com/settings/integrations/ "+
            "Please copy/paste it to the top of this document under "+
            "JOAN_CLIENT_ID and JOAN_CLIENT_SECRET variables."
          )
        }
        if(!ROOM_ID) {
          console.error(
            "Room ID not set. You can find it at: https://portal.getjoan.com/manage/resources/ "+
            "Please copy/paste it to the top of this document under "+
            "ROOM_ID"
          )
        }

        this.auth_token = "Authorization: Basic " + btoa((JOAN_CLIENT_ID+":"+JOAN_CLIENT_SECRET));
        this._portalAccessToken = null
    }
    
    static _isCiscoSWVersionSupported(versionString) {
     /* 
      * Check if Software version installed on Cisco device
      * supports http requests. Functionality is supported from 
      * CE9.8.0 forward
      */
      try {
        const version = SW_REGEX.exec(versionString)[0];
        console.log("Detected Cisco SW version: "+version);
      
        let [major, minor, patch] = version.split('.');
        if(SW_MIN[0] < parseInt(major)) {
          return true;
        } else if(SW_MIN[0] == parseInt(major) && SW_MIN[1] <= parseInt(minor)) {
          return true;
        } else {
          return false;
        }
      } catch(err) {
          console.error("Couldn't detect software version: ", err);
          return false;
      }
    }
    
    static _addMinutes(dt, seconds) {
      return new Date(dt.getTime() + seconds*1000);
    }
    
    async _getVersion() {
      /* Helper for getting the Cisco equipment 
       * software version.
       */
      return xapi.status.get("SystemUnit Software Version").then((version) => {
        if(!JoanAPI._isCiscoSWVersionSupported(version)) throw new Error("Software version 9.8.0 or above needed...");
          console.log("Software supported");
      }).catch(error =>console.log(error))
    }
    
    async _request(url, type, headers, body=null) {
      /* 
       * Wrapper for making http request through xapi command
       */
      console.log("Sending API request: ", body);
      switch(type) {
        case 'GET':
          return xapi.command('HttpClient Get', { 'Header': headers, 'Url':url});
        case 'POST':
          return xapi.command('HttpClient Post', { 'Header': headers, 'Url':url, ResultBody: 'plaintext'}, body);
        case 'PUT':
          return xapi.command('HttpClient Put', { 'Header': headers, 'Url':url, ResultBody: 'plaintext'}, body);
      }
    }

    async _checkAccessToken() {
      /* 
       * Helper function to get the access token from Joan Portal
       * using user client id and secret
       */
      console.log("Checking if valid access token...");
      if(!this._portalAccessToken || (this._portalAccessToken.expires < new Date())) {
          return new Promise((resolve, reject) => {
            console.log("Getting new access token...");
            this._request(PORTAL_BASE_URL+"/api/token/", "POST",
             ["Content-Type: application/x-www-form-urlencoded", this.auth_token],
              "grant_type=client_credentials"
            )
            .then((res) => {
              if (res.status == 'OK') { return res.Body; }
              else { reject(res.statusText); }
            })
            .then(body => {
              console.log("Got new access token ", new Date());
              this._portalAccessToken = JSON.parse(body)
              this._portalAccessToken.expires = JoanAPI._addMinutes(new Date(), this._portalAccessToken.expires_in);
              resolve(true);
            }).
            catch((error) => {
              console.log(error);
              reject(error);
            })
          })
        }
      }

    async init() {
      console.log("Initializing API...");
      console.log("Checking software version...");
      await this._getVersion();
      await this._checkAccessToken().catch((error) => console.log(error));
    }
    
    async postPresenceData(presence, people) {
      /* 
       * Helper function to post presence information
       * to Joan API and automatically book/end/check-in
       * to a meeting.
       */
      await this._checkAccessToken();
      this._request(
        PORTAL_BASE_URL+"/api/v1.0/accessories/presence/",
        "POST",
        ["Content-Type: application/json", "Authorization: Bearer "+this._portalAccessToken.access_token],
        JSON.stringify({
          'room':ROOM_ID,
          'presence': presence,
          'number_of_people':people,
          'type':"cisco"
        })
        ).then((res)=>{
          if(res.StatusCode === '204') {
            console.log("Presence data succesfully posted! | Presence: "+ presence+" | Number of detected people: "+people+" |")
          } else {
            throw new Error("Couldn't send presence data ",res)
          }
        }).catch(error => console.error(error));
    }
}

async function beginDetection() {
  /*
   * Entry point for the macro
   */
  const api = new JoanAPI(JOAN_CLIENT_ID, JOAN_CLIENT_SECRET);
  const presence = new PresenceDetector();
  
  await api.init();
  await presence.enableDetector();
  
  // we set the interval to poll Cisco equipment for the
  // presence information
  setInterval(async() => {
    await presence.updatePresence();
        if(presence.shouldSendAPI) {
            const currentPreseceData = presence.presenceData;
            presence.apiSent();

            console.log("sending API call!");
            api.postPresenceData(
              currentPreseceData.peoplePresence,
              currentPreseceData.peopleCount
            );
        }
    }, 
    POOL_INTERVAL_IN_SEC * 1000
  );
}

beginDetection();
