<?php
/*
 * Copyright 2008-2010 GuardTime AS
 *
 * This file is part of the GuardTime PHP SDK.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @package tsp
 */

/**
 * Object representing a single entry in a GTHashChain.
 * @package tsp
 */
class GTHashEntry {

    private $hashAlgorithm;
    private $direction;
    private $siblingHash;
    private $level;

    /**
     * Construct a new GTHashEntry instance.
     *
     * @param  GTHashAlgorithm $hashAlgorithm
     * @param  int $direction
     * @param  GTDataHash $siblingHash
     * @param  int $level
     */
    public function __construct(GTHashAlgorithm $hashAlgorithm, $direction, GTDataHash $siblingHash, $level) {

        $this->hashAlgorithm = $hashAlgorithm;
        $this->direction = $direction;
        $this->siblingHash = $siblingHash;
        $this->level = $level;

    }

    /**
     * Computes the output of this hash entry with given bytes.
     *
     * @param  array $bytes bytes to compute output for
     * @return array the result
     */
    public function computeOutput(array $bytes) {

        $hash = new GTDataHash($this->hashAlgorithm);

        $hash->update($bytes);
        $hash->close();

        $imprint1 = $hash->getDataImprint();
        $imprint2 = $this->siblingHash->getDataImprint();

        $output = array();

        if ($this->direction == 0) {

            foreach ($imprint2 as $byte) {
                array_push($output, $byte);
            }

            foreach ($imprint1 as $byte) {
                array_push($output, $byte);
            }

        } else {

            foreach ($imprint1 as $byte) {
                array_push($output, $byte);
            }

            foreach ($imprint2 as $byte) {
                array_push($output, $byte);
            }

        }

        array_push($output, $this->level);

        return $output;

    }

    /**
     * Gets the direction of this hash entry.
     *
     * @return int direction of this hash entry
     */
    public function getDirection() {
        return $this->direction;
    }

    /**
     * Gets the level of this hash entry.
     *
     * @return int level of this hash entry
     */
    public function getLevel() {
        return $this->level;
    }

}

?>
