/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: pxerror.cpp,v 1.3.24.1 2004/07/09 01:54:51 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

// system
#include "hlxclib/stdio.h"
#include "hlxclib/string.h"

// include
#include "hxtypes.h"
#include "hxcom.h"
#include "hxresult.h"
#include "hxcomm.h"
#include "ihxpckts.h"
#include "hxxres.h"
#include "hxxrsmg.h"

// coreres
#include "pixres.h"

// pxcomlib
#include "pxerror.h"

// hxdebug
#include "hxassert.h"
#include "hxheap.h"
#ifdef _DEBUG
#undef HX_THIS_FILE     
static char HX_THIS_FILE[] = __FILE__;
#endif

const PXError::PXErrorString PXError::m_pErrorTable[] = 
{
    { IDS_ERR_PIX_NOTLICENSED,     ERRSTR_PIX_NOTLICENSED     },
    { IDS_ERR_PIX_BADEXTENSION,    ERRSTR_PIX_BADEXTENSION    },
    { IDS_ERR_PIX_NOCODEC,         ERRSTR_PIX_NOCODEC         },
    { IDS_ERR_PIX_MISSINGFILE,     ERRSTR_PIX_MISSINGFILE     },
    { IDS_ERR_PIX_NOSTART,         ERRSTR_PIX_NOSTART         },
    { IDS_ERR_PIX_NOEND,           ERRSTR_PIX_NOEND           },
    { IDS_ERR_PIX_NOXMLEND,        ERRSTR_PIX_NOXMLEND        },
    { IDS_ERR_PIX_NULLTITLE,       ERRSTR_PIX_NULLTITLE       },
    { IDS_ERR_PIX_NULLAUTHOR,      ERRSTR_PIX_NULLAUTHOR      },
    { IDS_ERR_PIX_NULLCOPYRIGHT,   ERRSTR_PIX_NULLCOPYRIGHT   },
    { IDS_ERR_PIX_NULLVERSION,     ERRSTR_PIX_NULLVERSION     },
    { IDS_ERR_PIX_BADTIMEFORMAT,   ERRSTR_PIX_BADTIMEFORMAT   },
    { IDS_ERR_PIX_BADSTARTTIME,    ERRSTR_PIX_BADSTARTTIME    },
    { IDS_ERR_PIX_BADPREROLL,      ERRSTR_PIX_BADPREROLL      },
    { IDS_ERR_PIX_NULLURL,         ERRSTR_PIX_NULLURL         },
    { IDS_ERR_PIX_URLALLWHITE,     ERRSTR_PIX_URLALLWHITE     },
    { IDS_ERR_PIX_BADDURATION,     ERRSTR_PIX_BADDURATION     },
    { IDS_ERR_PIX_ZERODURATION,    ERRSTR_PIX_ZERODURATION    },
    { IDS_ERR_PIX_NOBITRATE,       ERRSTR_PIX_NOBITRATE       },
    { IDS_ERR_PIX_BADBITRATE,      ERRSTR_PIX_BADBITRATE      },
    { IDS_ERR_PIX_NOWIDTH,         ERRSTR_PIX_NOWIDTH         },
    { IDS_ERR_PIX_NOHEIGHT,        ERRSTR_PIX_NOHEIGHT        },
    { IDS_ERR_PIX_UNKNOWNTAG,      ERRSTR_PIX_UNKNOWNTAG      },
    { IDS_ERR_PIX_INVALIDHEAD,     ERRSTR_PIX_INVALIDHEAD     },
    { IDS_ERR_PIX_NOEFFECTS,       ERRSTR_PIX_NOEFFECTS       },
    { IDS_ERR_PIX_NODURNOEFFECT,   ERRSTR_PIX_NODURNOEFFECT   },
    { IDS_ERR_PIX_INVALIDEFFECTS,  ERRSTR_PIX_INVALIDEFFECTS  },
    { IDS_ERR_PIX_NOHANDLE,        ERRSTR_PIX_NOHANDLE        },
    { IDS_ERR_PIX_BADHANDLE,       ERRSTR_PIX_BADHANDLE       },
    { IDS_ERR_PIX_NONAME,          ERRSTR_PIX_NONAME          },
    { IDS_ERR_PIX_NULLNAME,        ERRSTR_PIX_NULLNAME        },
    { IDS_ERR_PIX_BADEFFECT,       ERRSTR_PIX_BADEFFECT       },
    { IDS_ERR_PIX_GENERALERROR,    ERRSTR_PIX_GENERALERROR    },
    { IDS_ERR_PIX_BADASPECTFLAG,   ERRSTR_PIX_BADASPECTFLAG   },
    { IDS_ERR_PIX_UNKHEADATTR,     ERRSTR_PIX_UNKHEADATTR     },
    { IDS_ERR_PIX_BADATTRIBUTE,    ERRSTR_PIX_BADATTRIBUTE    },
    { IDS_ERR_PIX_MISSINGSTART,    ERRSTR_PIX_MISSINGSTART    },
    { IDS_ERR_PIX_MISSINGDURATION, ERRSTR_PIX_MISSINGDURATION },
    { IDS_ERR_PIX_MISSINGCOLOR,    ERRSTR_PIX_MISSINGCOLOR    },
    { IDS_ERR_PIX_BADCOLOR,        ERRSTR_PIX_BADCOLOR        },
    { IDS_ERR_PIX_MISSINGTARGET,   ERRSTR_PIX_MISSINGTARGET   },
    { IDS_ERR_PIX_MISSINGNAME,     ERRSTR_PIX_MISSINGNAME     },
    { IDS_ERR_PIX_MISSINGPACKAGE,  ERRSTR_PIX_MISSINGPACKAGE  },
    { IDS_ERR_PIX_BADBOOL,         ERRSTR_PIX_BADBOOL         },
    { IDS_ERR_PIX_BADWIPEDIR,      ERRSTR_PIX_BADWIPEDIR      },
    { IDS_ERR_PIX_BADWIPETYPE,     ERRSTR_PIX_BADWIPETYPE     },
    { IDS_ERR_PIX_BADBGCOLOR,      ERRSTR_PIX_BADBGCOLOR      },
    { IDS_ERR_PIX_ILLEGALATTR,     ERRSTR_PIX_ILLEGALATTR     },
    { IDS_ERR_PIX_MISSREQATTR,     ERRSTR_PIX_MISSREQATTR     },
    { IDS_ERR_PIX_ROOTNOTFIRST,    ERRSTR_PIX_ROOTNOTFIRST    },
    { IDS_ERR_PIX_HEADNOTFIRST,    ERRSTR_PIX_HEADNOTFIRST    },
    { IDS_ERR_PIX_BADATTRVALUE,    ERRSTR_PIX_BADATTRVALUE    },
    { IDS_ERR_PIX_BADDSTRECT,      ERRSTR_PIX_BADDSTRECT      },
    { IDS_ERR_PIX_BADCENTERFLAG,   ERRSTR_PIX_BADCENTERFLAG   },
    { IDS_ERR_PIX_FUTUREVERSION,   ERRSTR_PIX_FUTUREVERSION   },
    { IDS_ERR_PIX_INCOMPATVERSION, ERRSTR_PIX_INCOMPATVERSION },
    { IDS_ERR_PIX_DUPHANDLE,       ERRSTR_PIX_DUPHANDLE       },
    { IDS_ERR_PIX_ZEROSIZE,        ERRSTR_PIX_ZEROSIZE        },
    { 0,                           NULL                       }
};

PXError::PXError(IUnknown* pContext)
{
    if (pContext)
    {
        m_pContext = pContext;
        m_pContext->AddRef();
    }
}

PXError::~PXError()
{
    HX_RELEASE(m_pContext);
}

HX_RESULT PXError::SetError(UINT32 ulErrorID, UINT32 ulLine, UINT32 ulCol,
                            const char* pszArg1, const char* pszArg2,
                            REF(IHXBuffer*) rpErrStr)
{
    HX_RESULT retVal = HXR_OK;

    const char*    pszFormat = NULL;
    IHXXResource* pRes      = NULL;
    retVal                   = GetErrorResource(ulErrorID, pRes);
    if (SUCCEEDED(retVal))
    {
        pszFormat = (const char*) pRes->ResourceData();
    }
    else
    {
        retVal = GetDefaultErrorFormatString(ulErrorID, pszFormat);
    }

    if (SUCCEEDED(retVal))
    {
        // Make sure num args provided and num args in format string match up
        UINT32 ulNumFormatArgs = CountArguments(pszFormat);
        UINT32 ulNumArgs       = 0;
        if (pszArg1)
        {
            ulNumArgs++;
        }
        if (pszArg2)
        {
            ulNumArgs++;
        }
        // Only display the error if the number of arguments match up
        HX_ASSERT(ulNumFormatArgs == ulNumArgs);
        if (ulNumFormatArgs == ulNumArgs)
        {
            // Create a new format string with line and column in it
            // pszFormat is the format string we got from the resource lookup
            // pszFormat1 is the template for the new format string
            // pszFormat2 is the new format string
            // Max size of pszFormat2 = strlen(pszFormat1) +
            //                          strlen(pszFormat)  +
            //                          2*MAX_UINT32_STRING_SIZE + 1
            //                        = strlen(") + strlen(") + 21
            const char* pszFormat1 = "%s (line %lu, column %lu)";
            UINT32      ulMaxSize  = strlen(pszFormat1) + strlen(pszFormat) + 21;
            char*       pszFormat2 = new char [ulMaxSize];
            if (pszFormat2)
            {
                // Create the new format string
                sprintf(pszFormat2, pszFormat1, pszFormat, ulLine, ulCol); /* Flawfinder: ignore */
                // Create the error string
                //
                // Max size of error string = strlen(pszFormat2) +
                //                            strlen(pszArg1)    +
                //                            strlen(pszArg2)    + 1
                // 
                ulMaxSize = strlen(pszFormat2) +
                            (pszArg1 ? strlen(pszArg1) : 0) +
                            (pszArg2 ? strlen(pszArg2) : 0) + 1;
                char* pszErr = new char [ulMaxSize];
                if (pszErr)
                {
                    switch(ulNumArgs)
                    {
                        case 0:
                            strcpy(pszErr, pszFormat2); /* Flawfinder: ignore */
                            break;
                        case 1:
                            sprintf(pszErr, pszFormat2, pszArg1); /* Flawfinder: ignore */
                            break;
                        case 2:
                            sprintf(pszErr, pszFormat2, pszArg1, pszArg2); /* Flawfinder: ignore */
                            break;
                        default:
                            pszErr[0] = '\0';
                    }

                    retVal = SetString(pszErr, rpErrStr);
                }
                HX_VECTOR_DELETE(pszErr);
            }
            HX_VECTOR_DELETE(pszFormat2);
        }
    }
    HX_RELEASE(pRes);

    return retVal;
}

HX_RESULT PXError::SetError(UINT32 ulErrorID, const char* pszArg1,
                            const char* pszArg2, REF(IHXBuffer*) rpErrStr)
{
    HX_RESULT retVal = HXR_OK;

    const char*    pszFormat = NULL;
    IHXXResource* pRes      = NULL;
    retVal                   = GetErrorResource(ulErrorID, pRes);
    if (SUCCEEDED(retVal))
    {
        pszFormat = (const char*) pRes->ResourceData();
    }
    else
    {
        retVal = GetDefaultErrorFormatString(ulErrorID, pszFormat);
    }

    if (SUCCEEDED(retVal))
    {
        // Make sure num args provided and num args in format string match up
        UINT32 ulNumFormatArgs = CountArguments(pszFormat);
        UINT32 ulNumArgs       = 0;
        if (pszArg1)
        {
            ulNumArgs++;
        }
        if (pszArg2)
        {
            ulNumArgs++;
        }
        // Only display the error if the number of arguments match up
        HX_ASSERT(ulNumFormatArgs == ulNumArgs);
        if (ulNumFormatArgs == ulNumArgs)
        {
            // Create error string
            //
            // Max size of error string = strlen(pszFormat) +
            //                            strlen(pszArg1)   +
            //                            strlen(pszArg2)   + 1
            UINT32 ulMaxSize = strlen(pszFormat)               +
                               (pszArg1 ? strlen(pszArg1) : 0) +
                               (pszArg2 ? strlen(pszArg2) : 0) + 1;
            char* pszErr = new char [ulMaxSize];
            if (pszErr)
            {
                switch (ulNumArgs)
                {
                    case 0:
                        strcpy(pszErr, pszFormat); /* Flawfinder: ignore */
                        break;
                    case 1:
                        sprintf(pszErr, pszFormat, pszArg1); /* Flawfinder: ignore */
                        break;
                    case 2:
                        sprintf(pszErr, pszFormat, pszArg1, pszArg2); /* Flawfinder: ignore */
                        break;
                    default:
                        pszErr[0] = '\0';
                }

                retVal = SetString(pszErr, rpErrStr);
            }
            HX_VECTOR_DELETE(pszErr);
        }
    }
    HX_RELEASE(pRes);

    return retVal;
}

HX_RESULT PXError::SetError(const char* pszFileName, UINT32 ulErrorID, UINT32 ulLine,
                            UINT32 ulCol, const char* pszArg1, const char* pszArg2,
                            REF(IHXBuffer*) rpErrStr)
{
    HX_RESULT retVal = HXR_OK;

    const char*    pszFormat = NULL;
    IHXXResource* pRes      = NULL;
    retVal                   = GetErrorResource(ulErrorID, pRes);
    if (SUCCEEDED(retVal))
    {
        pszFormat = (const char*) pRes->ResourceData();
    }
    else
    {
        retVal = GetDefaultErrorFormatString(ulErrorID, pszFormat);
    }

    if (SUCCEEDED(retVal))
    {
        // Make sure num args provided and num args in format string match up
        UINT32 ulNumFormatArgs = CountArguments(pszFormat);
        UINT32 ulNumArgs       = 0;
        if (pszArg1)
        {
            ulNumArgs++;
        }
        if (pszArg2)
        {
            ulNumArgs++;
        }
        // Only display the error if the number of arguments match up
        HX_ASSERT(ulNumFormatArgs == ulNumArgs);
        if (ulNumFormatArgs == ulNumArgs)
        {
            // Create a new format string from the resource format string
            //
            const char* pszFormat1 = "(%s): %s (line %lu, column %lu)";
            // The max size of the new format string = strlen(pszFormat1)  +
            //                                         strlen(pszFileName) +
            //                                         strlen(pszFormat)   +
            //                                         2*MAX_SIZE_OF_UINT32 string + 1
            //                                       = strlen(") + strlen(") + strlen(") + 21;
            UINT32 ulMaxSize = strlen(pszFormat1)  +
                               strlen(pszFileName) +
                               strlen(pszFormat)   + 21;
            char* pszFormat2 = new char [ulMaxSize];
            if (pszFormat2)
            {
                // Create the format string
                sprintf(pszFormat2, pszFormat1, pszFileName, pszFormat, ulLine, ulCol); /* Flawfinder: ignore */
                // Create the error string
                //
                // The max size of the error string = strlen(pszFormat2) +
                //                                    strlen(pszArg1)    +
                //                                    strlen(pszArg2)    + 1
                ulMaxSize = strlen(pszFormat2) +
                            (pszArg1 ? strlen(pszArg1) : 0) +
                            (pszArg2 ? strlen(pszArg2) : 0) + 1;
                char* pszErr = new char [ulMaxSize];
                if (pszErr)
                {
                    switch (ulNumArgs)
                    {
                        case 0:
                            strcpy(pszErr, pszFormat2); /* Flawfinder: ignore */
                            break;
                        case 1:
                            sprintf(pszErr, pszFormat2, pszArg1); /* Flawfinder: ignore */
                            break;
                        case 2:
                            sprintf(pszErr, pszFormat2, pszArg1, pszArg2); /* Flawfinder: ignore */
                            break;
                        default:
                            pszErr[0] = '\0';
                    }

                    retVal = SetString(pszErr, rpErrStr);
                }
                HX_VECTOR_DELETE(pszErr);
            }
            HX_VECTOR_DELETE(pszFormat2);
        }
    }
    HX_RELEASE(pRes);

    return retVal;
}

HX_RESULT PXError::GetErrorResource(UINT32 ulErrorID, REF(IHXXResource*) rpResource)
{
    HX_RESULT retVal = HXR_OK;

    if (m_pContext)
    {
        IHXExternalResourceManager* pMgr = NULL;
        retVal = m_pContext->QueryInterface(IID_IHXExternalResourceManager, (void**) &pMgr);
        if (SUCCEEDED(retVal))
        {
            IHXExternalResourceReader* pRdr = NULL;
            retVal = pMgr->CreateExternalResourceReader(CORE_RESOURCE_SHORT_NAME, pRdr);
            if (SUCCEEDED(retVal))
            {
                IHXXResource* pRes = pRdr->GetResource(HX_RT_STRING, ulErrorID);
                if(pRes)
                {
                    HX_RELEASE(rpResource);
                    rpResource = pRes;
                    rpResource->AddRef();
                }
                else
                {
                    retVal = HXR_FAIL;
                }
                HX_RELEASE(pRes);
            }
            HX_RELEASE(pRdr);
        }
        HX_RELEASE(pMgr);
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

HX_RESULT PXError::GetDefaultErrorFormatString(UINT32 ulErrorID, REF(const char*) rpszFormat)
{
    HX_RESULT retVal = HXR_FAIL;

    // Search the table
    PXErrorString* pErr = (PXErrorString*) m_pErrorTable;
    while (pErr->m_pszString)
    {
        if (ulErrorID == pErr->m_ulStringID)
        {
            break;
        }
        pErr++;
    }

    // Assign the out parameter
    if (pErr->m_pszString)
    {
        rpszFormat = pErr->m_pszString;
        retVal     = HXR_OK;
    }

    return retVal;
}

HX_RESULT PXError::SetString(const char* pszErr, REF(IHXBuffer*) rpErrStr)
{
    HX_RESULT retVal = HXR_OK;

    if (m_pContext)
    {
        IHXCommonClassFactory* pFactory = NULL;
        retVal = m_pContext->QueryInterface(IID_IHXCommonClassFactory,
                                            (void**) &pFactory);
        if (SUCCEEDED(retVal))
        {
            IHXBuffer* pBuffer = NULL;
            retVal = pFactory->CreateInstance(CLSID_IHXBuffer, (void**) &pBuffer);
            if (SUCCEEDED(retVal))
            {
                retVal = pBuffer->Set((const unsigned char*) pszErr,
                                      strlen(pszErr) + 1);
                if (SUCCEEDED(retVal))
                {
                    HX_RELEASE(rpErrStr);
                    rpErrStr = pBuffer;
                    rpErrStr->AddRef();
                }
            }
            HX_RELEASE(pBuffer);
        }
        HX_RELEASE(pFactory);
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

UINT32 PXError::CountArguments(const char* pszFormat)
{
    UINT32 ulRet = 0;

    if (pszFormat)
    {
        char* pszPct = (char*) pszFormat;
        do
        {
            pszPct = (char*)strchr((const char*) pszPct, '%');
            if (pszPct)
            {
                ulRet++;
                pszPct++;
            }
        }
        while (pszPct);
    }

    return ulRet;
}

