classdef credentials
  properties
  
    hostname = [];
    database = [];
    username = [];
    password = [];
    expiry = 0;
    
  end % properties

  methods

    % contructor
    function obj = credentials(hostname, database, username, password)
      switch nargin
        case 1
          obj.hostname = hostname;
        case 2
          obj.hostname = hostname;
          obj.database = database;
        case 3
          obj.hostname = hostname;
          obj.database = database;
          obj.username = username;
        case 4
          obj.hostname = hostname;
          obj.database = database;
          obj.username = username;
          obj.password = password;
      end
    end

    % convert to string representation
    function str = char(obj, mode)
      if nargin < 2
        mode = '';
      end
      switch mode
        case 'short'
          % do not show password
          frm = 'mysql://%s/%s username=%s';  
          str = sprintf(frm, obj.hostname, obj.database, obj.username);
        case 'full'
          % show password
          frm = 'mysql://%s/%s username=%s password=%s';
          str = sprintf(frm, obj.hostname, obj.database, obj.username, obj.password);
        otherwise
          % by default only show if a password is known              
          passwd = [];
          if ischar(obj.password)
            passwd = 'YES';
          end
          frm = 'mysql://%s/%s username=%s password=%s';
          str = sprintf(frm, obj.hostname, obj.database, obj.username, passwd);
      end
    end
    
    % display
    function disp(obj)
      disp(['    ' char(obj) char(10)]);
    end
    
    % check that a credentials object contails all the required informations
    function rv = complete(obj)
      info = {'hostname', 'database', 'username', 'password'};
      for kk = 1:numel(info)
        if isempty(obj.(info{kk}))
          rv = false;
          return;
        end
      end
      rv = true;
    end
    
    % check if the credentials are expired
    function rv = expired(obj)
      rv = false;
      if obj.expiry > 0 && double(time()) > obj.expiry
        rv = true;
      end
    end
    
    % check if the credentials object matches the given informations
    function rv = match(obj, hostname, database, username)
      if nargin < 4
        username = [];
      end
      
      % default value
      rv = true;
      
      if ~strcmp(obj.hostname, hostname)
        rv = false;
        return;
      end
      if ~strcmp(obj.database, database)
        rv = false;
        return;
      end
      if ischar(username) && ischar(obj.username) && ~strcmp(obj.username, username)
        rv = false;
        return;
      end
    end
    
  end % methods

end