package com.k_int.aggr2.mimsy.data.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

import com.k_int.aggr2.mimsy.data.MimsyDataDTO;
import com.k_int.aggr2.mimsy.rdf.RDFFormatConverter;
import com.k_int.mimsy.ref.DataException;



public class MimsyHelper
{

	
	public static long getChecksum(MimsyDataDTO data)throws DataException
	{
		  RDFFormatConverter converter 	= new RDFFormatConverter();
		  byte[] bytes 					= converter.convert(data);
		  Checksum checksum 			= new CRC32();
		  checksum.update(bytes,0,bytes.length);
		  long checksum_val 			= checksum.getValue();
		  return checksum_val;
	}
	
	
	public static String getDateString(Date date)
	{
		return date.toString();
	}
	
	public static long getChecksum(String val)throws DataException
	{
		try
		{
		  byte[] bytes 					= val.getBytes("UTF8");
		  Checksum checksum 			= new CRC32();
		  checksum.update(bytes,0,bytes.length);
		  long checksum_val 			= checksum.getValue();
		  return checksum_val;
		}
		catch(Exception e)
		{
			throw new DataException(e);
		}
	}
	
	
    public static String encodeForXml(String value) throws DataException
    {
        if (value != null) 
        {
            if(value.indexOf("&")==-1 && value.indexOf("<")==-1 && value.indexOf((char)0x0)==-1)
                return value.trim();
                            
            try
            {    
              value=value.trim();
              byte[] bytes                  = value.getBytes("UTF-8");              
              ByteArrayOutputStream baos    = new ByteArrayOutputStream();              
              BufferedWriter writer         = new BufferedWriter(new OutputStreamWriter(baos,"UTF-8"));
              
              for(int i=0;i<bytes.length;i++)
              {
                  byte bite = bytes[i];
                  
                  if(bite==38)
                  {
                      writer.write("&amp;");
                      writer.flush();                   
                  }
                  else if (bite==60)
                  {
                      writer.write("&lt;");
                      writer.flush();                      
                  }
                  else if (bite==(char)0x0)
                  {
                	  
                  }
                  else
                  {
                      baos.write(bite);
                      baos.flush();
                  }                 
              }
             
              writer.close();
              return baos.toString("UTF-8");            
          }
          catch(Exception e)
          {
            throw new DataException(e);
          }
         }

        return value;
    }
    
}
