package de.tu_dresden.diplom.richter_mirko_mat2628335.common.entity;

import org.apache.log4j.Logger;

import javax.security.auth.x500.X500Principal;
import java.security.Key;
import java.security.cert.X509Certificate;

/**
 * Class that represents a particular entity that may perform several actions
 * on the systems if it is allowed to.
 */
public class Entity implements IFEntity{

   private static final Logger logger = Logger.getLogger(Entity.class);

   private int id = 0;
   private X509Certificate signatureCertificate = null;

   /**
    * @see IFEntity#getPublicSignatureKeyValue()
    */
   public Key getPublicSignatureKeyValue() {
      Key result = null;
      if(getSignatureCertificate() != null){
         result = getSignatureCertificate().getPublicKey();
      }
      return result;
   }

   /**
    * @see IFEntity#getSignatureCertificate() 
    */
   public X509Certificate getSignatureCertificate() {
      return signatureCertificate;
   }

   /**
    * Sets the certificate that is being used to validate some signature.
    * @param signatureCertificate
    */
   public void setSignatureCertificate(X509Certificate signatureCertificate) {
      this.signatureCertificate = signatureCertificate;
   }

   /**
    * Generates a human-readable string-representation out of this object
    * @return
    */
   public String toString() {
      X509Certificate cert = getSignatureCertificate();
      X500Principal principal = cert.getSubjectX500Principal();
      //return getSignatureCertificate().getSubjectX500Principal().toString();
      return principal.toString();
   }

   /**
    * @see IFEntity#getId()
    */
   public int getId() {
      return id;
   }

   /**
    * Sets the id (internal representation of some entity) of the entity.
    * @param id the new id
    */
   public void setId(int id) {
      this.id = id;
   }

   /**
    * Checks wheather this entity equals the given object
    * @param obj the object to compare with
    * @return true if equals, false else
    */
   public boolean equals(Object obj) {
      boolean result = false;
      if(this == obj){
         result = true;
      }else{
         if(obj instanceof IFEntity && obj != null){
            result = ((IFEntity)obj).getPublicSignatureKeyValue().equals(getPublicSignatureKeyValue());
         }
      }
      return result;
   }
}
