// ************************************************************************************************************
// Author: Marcin Załęczny
// Release Date: 2010-11-08
// Licence: The GNU Lesser General Public License, version 3.0 (LGPLv3)
// ************************************************************************************************************
#include "mzXpsRelationships.h"
#include "mzStringList.h"

CXpsRelationships::CXpsRelationships()
    : CXmlDocument(L"Relationships")
{
    this->setRealClassName(L"CXpsRelationships");
}

CXpsRelationships::CXpsRelationships(CString xmlVersion, CString xmlEncoding)
    : CXmlDocument(L"Relationships", xmlVersion, xmlEncoding)
{
    this->setRealClassName(L"CXpsRelationships");
}

CXpsRelationships::~CXpsRelationships() {
}

BOOL CXpsRelationships::addRelationship(CString target, CString id, CString type) {
    CXmlNode* item = new CXmlNode(L"Relationship");
    if (item) {
        item->addAttribute(L"Target", target);
        item->addAttribute(L"Id", id);
        item->addAttribute(L"Type", type);
        this->_items->append((LONG)item);
        return TRUE;
    }
    
    return FALSE;
}

BOOL CXpsRelationships::removeRelationship(CString target, CString id, CString type) {
    CXmlNode* item = this->getFirstChildWithAttribs(L"Relationship", L"Target", target, L"Id", id, L"Type", type);
    if (item) {
        return this->removeItem(item);
    }
    
    return FALSE;
}

CString CXpsRelationships::getFirstAvailableId() {
    CStringList* attribs = CXmlDocument::createListOfAllItemsAttributeValues(this->_items, L"Relationship", L"Id");
    CString retval(L"R0");
    INT attrSize = attribs->size();
    
    if (attrSize > 0) {
        CArrayList* lst = new CArrayList(attrSize);
        CString id;
        UINT i;
        
        for (i = 0; i < attrSize; i++) {
            id = attribs->getAt(i);
            id.ltrim(L'R');
            lst->append(id.toInt());
        }
        lst->sort();
        
        LONG* items = lst->getItemsBuf();
        if (items[0] == 0) {
            if (attrSize == 1) {
                retval = L"R1";
            } else {
                i = 1;
                while (i < attrSize && items[i] - items[i-1] == 1) {
                    i++;
                }
                retval = CString(L"R") + (items[i-1] + 1);
            }
        }
        delete lst;
    }
    
    delete attribs;
    return retval;
}
