<?php

namespace apexl\hashing;

use apexl\hashing\interfaces\Hashing;

class Hash
{
    protected string $type;
    protected Hashing $hash;
    protected string $salt;

    public function __construct($hashType = 'Blowfish')
    {
        $this->setHash($hashType);
    }

    public function setHash($hashType, $namespace = "\\apexl\\hashing\\drivers\\")
    {
        //We need to be able to check that the hash we're using implements the appropriate interface.
        $hashingClass = $namespace . $hashType;
        $this->confirmHash(new $hashingClass());
    }

    protected function confirmHash(Hashing $hash)
    {
        $this->hash = $hash;
    }

    /**
     * function to hash the passed string. If no salt is provided, we generate one.
     * @param $string
     * @param string|false $salt
     * @return object
     */
    public function hashString($string, $salt = false): object
    {
        if (!$salt) {
            $salt = $this->hash::generateRandomSalt();
        }
        $hashedString = $this->hash::hashString($string, $salt);
        return (object)['string' => $string, 'salt' => $salt, 'hash' => $hashedString];
    }

    public function generateRandomHash(): string
    {
        return $this->hash::generateRandomHash();
    }

    /**
     * Function to confirm if the passed string matches the passed hash and salt.
     * @param $string
     * @param $hash
     * @param $salt
     * @return bool
     */
    public function matchHash($string, $hash, $salt): bool
    {
        $stringHash = $this->hash::hashString($string, $salt);

        return $hash === $stringHash;
    }
}
