<?php

namespace AuthStack\UserDirectory\Provider;

use AuthStack\UserDirectory\AUD;
use Illuminate\Support\ServiceProvider;

class AUDProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('AUD', function($app)
        {
            $aud = new AUD(env('AUD_URL'), base64_encode(env('AUD_TOKEN')));

            if(request()->hasHeader('X-TimeZoneOffset') && request()->hasHeader('X-TimeZoneDST'))
            {
                $aud->setTimeZoneOffset((string)request()->header('X-TimeZoneOffset'));
                $aud->setTimeZoneDST((string)request()->header('X-TimeZoneDST'));
            }

            if(config('aud.policy.enforce'))
            {
                $aud->setDefaultPasswordPolicyID((int)config('aud.policy.id'));
            }

            return $aud;
        });

        $this->mergeConfig();
    }

    public function boot()
    {
        $this->publishes([
            $this->getConfigPath() => config_path('aud.php')
        ], 'audconfig');
    }

    private function mergeConfig()
    {
        $path = $this->getConfigPath();

        $this->mergeConfigFrom($path, 'aud');
    }

    protected function getConfigPath()
    {
        return __DIR__ . '/../../config/aud.php';
    }
}