/***********************************************************************
 * 
 *  Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; version 2.1
 *  of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, Novell, Inc.
 * 
 *  To contact Novell about this file by physical or electronic mail, 
 *  you may find current contact information at www.novell.com.
 * 
 ***********************************************************************/

using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.cache;
using sscs.common;
using sscs.constants;
namespace sscs.verbs 
{
    
   /*
    * This class is implementation of EnumerateKeyChainIds call.
    * There will be one instance existing for every call made by the client.  
    */

    internal class EnumerateKeyChainIds : SSVerb
    {
        private ushort msgId = 0;
        private uint inMsgLen  = 0;
        private uint outMsgLen = 0;
        private int retCode = 0;

        private byte[] inBuf;
        private byte[] outBuf;
        
        /*
        * This method sets the class member with the byte array received.
        */
 
        public void SetMessageContent(byte[] ipcBytes)
        {
           CSSSLogger.ExecutionTrace(this);
           inBuf = ipcBytes;                   
        }

       /*
        * This method does the actual implementation of EnumerateKeyChainIds 
        *   
        */

        public byte[] ProcessRequest(UserIdentifier userId)
        {
            CSSSLogger.ExecutionTrace(this);
            int keyChainIdsLen = 0;
            StringBuilder keyChainIds = new StringBuilder();
            /* If an exception occurs in message format decoding,
             * it is handled by AppHandler
             */

            // Message Format decipher - Start

            msgId          = BitConverter.ToUInt16(inBuf,0);
            inMsgLen       = BitConverter.ToUInt32(inBuf,2);
            if( inMsgLen != inBuf.Length )
                throw new FormatException(" MsgLen sent does not match the length of the message received.");
            
            // Message Format decipher - End
            try
            {
                int index = 0;
                SecretStore ssStore = SessionManager.GetUserSecretStore(userId);
                int numKeyChains = ssStore.GetNumKeyChains();
                IDictionaryEnumerator etor = (IDictionaryEnumerator)ssStore.GetKeyChainEnumerator();
                while(etor.MoveNext())
                {
                    index++;
                    keyChainIds.Append((string)etor.Key,0,(((string)(etor.Key)).Length)-1);
                    keyChainIdsLen += ((string)(etor.Key)).Length-1;
                    if( index != numKeyChains )
                    {
                        keyChainIds.Append("*");
                        keyChainIdsLen += 1;
                    }
                }
            }
            catch(UserNotInSessionException)
            {
                CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Unable to get user's secretstore" );
                retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
            }
            catch(Exception e)
            {
                CSSSLogger.ExpLog(e.ToString());
                retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
            }
                
            // Construct a Reply. 

            try
            {
                msgId = 4;
                outMsgLen = 14 + (uint)keyChainIds.Length;
                outBuf = new byte[outMsgLen];
                byte[] t = new byte[10];

                t = BitConverter.GetBytes((ushort)msgId);
                Array.Copy(t,0,outBuf,0,2);

                t = BitConverter.GetBytes((uint)outMsgLen);
                Array.Copy(t,0,outBuf,2,4);

                t = BitConverter.GetBytes(keyChainIdsLen);
                Array.Copy(t,0,outBuf,6,4);

                Encoding.UTF8.GetBytes(keyChainIds.ToString(),0,keyChainIds.Length,outBuf,10);

                t = BitConverter.GetBytes(retCode);
                Array.Copy(t,0,outBuf,(10+keyChainIds.Length),4);
            }
            catch(Exception e)
            {
                CSSSLogger.ExpLog(e.ToString());
                throw new FormatException("Unable to form the response " + e.ToString());
            }

            return outBuf;

        }


        /*
         * Gives the name of operation performed. Will be used in case 
         * of error. 
         */
        public string GetVerbName()
        {
            return this.ToString(); 
        }
    }
}