<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\CodeStructuralElement;

use function sha1;
use function sprintf;

class StructuralElementRelation
{
    /** @var string  */
    private $id;
    /** @var FullQualifiedStructuralElementName  */
    private $initiator;
    /** @var FullQualifiedStructuralElementName  */
    private $involved;
    /** @var StructuralElementRelationType  */
    private $type;
    /** @var array  */
    private $attributes;

    /**
     * StructuralElementRelation constructor.
     * @param FullQualifiedStructuralElementName $initiator
     * @param FullQualifiedStructuralElementName $involved
     * @param StructuralElementRelationType $type
     * @param array $attributes
     */
    public function __construct(
        FullQualifiedStructuralElementName $initiator,
        FullQualifiedStructuralElementName $involved,
        StructuralElementRelationType $type,
        array $attributes = []
    ) {
        $this->initiator = $initiator;
        $this->involved = $involved;
        $this->type = $type;
        $this->attributes = $attributes;
    }

    /**
     * @return string
     */
    public function getId(): string
    {
        if (!isset($this->id)) {
            $this->id = sha1(sprintf(
                '(%s)-%s-(%s)',
                (string)$this->getInitiator(),
                $this->getType(),
                (string)$this->getInvolved()
            ));
        }
        return $this->id;
    }

    /**
     * @return FullQualifiedStructuralElementName
     */
    public function getInitiator(): FullQualifiedStructuralElementName
    {
        return $this->initiator;
    }

    /**
     * @return FullQualifiedStructuralElementName
     */
    public function getInvolved(): FullQualifiedStructuralElementName
    {
        return $this->involved;
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return $this->type->getCode();
    }

    /**
     * @param string $type
     * @return bool
     */
    public function isCaseOf(string $type)
    {
        return $this->type->isCaseOf($type);
    }

    /**
     * @return array
     */
    public function getAttributes(): array
    {
        return $this->attributes;
    }
}
