import Axios from 'axios';
import * as url from 'url';
import { AmClient } from './am-client';

export class MtsAmClient extends AmClient {
  /**
   * Gets a user's profile.
   * Customized to supported API.
   */
  getProfile(userId: string, realm = 'root', sessionId: string, cookieName: string): Promise<any> {
    // var cookieName = cookieName;
    return Axios
      .get(`${this.serverAddress}/json/${realm}/users/${userId}`, {
        headers: {
          'Accept-API-Version': 'resource=3.0,protocol=1.0',
          'Content-Type': 'application/json',
          Host: this.hostname,
          [cookieName]: sessionId
        }
      })
      .then(res => res.data);
  }

  /**
   * Returns an OpenAM login URL with the goto query parameter set to the original URL in req.
   * Customized to accept service parameter, realm param unused.
   */
  getLoginUrl(goto?: string, realm = '/'): string {
    // FIXME hardcoded force HTTPS
    goto = goto.replace('http://', 'https://');
    const httpsServerUrl = this.serverUrl.replace('http://', 'https://');
    return httpsServerUrl + url.format({
      pathname: '/UI/Login',
      // FIXME hardcoded service
      query: { goto, 'realm': '/users', 'service': 'login' }
    });
  }

}
