package Opals::SIF::AckRegisterMsgHandler;

# Version number
$VERSION   = 0.01;


use warnings;
use strict;
use XML::XPath;
use XML::LibXML;
use Opals::SIF::Specs ;

sub new {
    my ($class) = @_;
    my $self={};

    bless $self, $class;
    return $self;
}

############################################################################################
#
#   REF:http://specification.sifinfo.org/Implementation/2.4/Messaging.html#Messaging
#
############################################################################################

sub processMsg{
    my ($self,$xmlMsg)=@_;
    my $parser   = XML::LibXML->new();
    eval { $parser->parse_string($xmlMsg); };
    my $rs={};
    if($@){
        $rs = {status=>0, error=>{desc=>"Invalid XML"}};
    }
    else{
        my $xmlObj =XML::XPath->new(xml=>$xmlMsg);
        if($xmlObj->exists(XPATH_ACK_ERROR)){
            my $error={code     =>$xmlObj->getNodeText(XPATH_ACK_ERROR_CODE),
                        category=>$xmlObj->getNodeText(XPATH_ACK_ERROR_CATEGORY),
                        desc    =>$xmlObj->getNodeText(XPATH_ACK_ERROR_DESC),
                        extDesc =>$xmlObj->getNodeText(XPATH_ACK_ERROR_EXTENDEDDESC)
                        };
            $rs = {status=>-1, error=>$error};

        }
        elsif($xmlObj->exists(XPATH_ACK_STATUS_CODE)){
            my $code=$xmlObj->getNodeText(XPATH_ACK_STATUS_CODE);
            $rs->{'status'} =$code;
            if ($code eq "0"){
                my ($dataObj) =$xmlObj->findnodes(XPATH_ACK_STATUS_DATA);
                $rs->{'acl'} =getAcl($xmlObj);
            }
            elsif($code eq "7"){
                $rs->{'error'}={desc=>"duplicate SIF_MsgId"};
            }
            elsif($code eq "8"){
                 $rs->{'error'}={desc=>"ZIS is asleep"};

            }
            else{
                $rs->{'error'}={desc=>"UNKNOW ERROR"};
            }

        }
        else{
            $rs = {status=>-1, error=>{desc=>"UNKNOW ERROR"}};
        }

    }
        
    return $rs;
   
}
############################################################################################
sub getAcl{
    my ($xmlObj) =@_;

    my @accessCtrl= qw(
    SIF_ProvideAccess
    SIF_SubscribeAccess 
    SIF_PublishAddAccess 
    SIF_PublishChangeAccess
    SIF_PublishDeleteAccess
    SIF_RequestAccess
    SIF_RespondAccess);

    my $acl={}; 
    my $xpath= XPATH_ACK_STATUS_DATA ."/SIF_AgentACL" ;
    if($xmlObj->exists()){
       foreach my $ac (@accessCtrl){
           if(my ($node)=$xmlObj->findnodes("$xpath/$ac/SIF_Object")){
                my $objName= $node->getAttribute("ObjectName"); 
                $acl->{$objName}->{$ac}=1;
            }
       }
    }

    return $acl;

}

############################################################################################
1;

