<?php

/**
 * User: sb
 * Date: 18.12.2015
 * Time: 09:00
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH
 * (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2014 Lifestyle Webconsulting GmbH
 * @version    $Id$
 * @link       www.life-style.de
 */

namespace LifeStyle\Tools\MfaBundle\Api\Mfa\Create;

use LifeStyle\Tools\MfaBundle\Api\Manager as MfaApiManager;
use LifeStyle\Tools\MfaBundle\Api\Mfa\Image\MfaException;
use LifeStyle\Tools\MfaBundle\MfaCreator;

/**
 * Class Index
 * https://github.com/stolendata/totp/blob/master/totp.php
 * @package LifeStyle\Tools\MfaBundle\Api\Mfa\Create
 */
class Index implements MfaCreator
{

    /**
     * @var array
     */
    protected $facSetter;

    /**
     * @var MfaApiManager
     */
    protected $mfaApiM;

    /**
     * @var MfaApiManager
     */
    private $mfaApiManager;

    /**
     * @var string
     */
    protected $base32Map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

    /**
     * Factory constructor.
     * @param MfaApiManager $mfaApiManager
     */
    public function __construct(MfaApiManager $mfaApiManager)
    {
        $this->mfaApiManager = $mfaApiManager;
    }

    /**
     * @return string
     * @throws MfaException
     */
    public function generateSecret()
    {
        $length = $this->mfaApiManager->mfa()->configuration()->getSecretLength();
        if ($length < 16 || $length % 8 != 0) {
            throw new MfaException('length must be a multiple of 8, and at least 16');
        }

        $secret = '';
        while ($length--) {
            $c = @gettimeofday()['usec'] % 53;
            while ($c--) {
                mt_rand();
            }
            @$secret .= $this->base32Map[mt_rand(0, 31)];
        }

        return $secret;
    }
}
