<?php

namespace Benhauer\Salesmanago\Model;

use \SALESmanago\Entity\Settings;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \SALESmanago\Model\SettingsInterface;
use \SALESmanago\Model\UserInterface as SmUserInterface;
use \SALESmanago\Factories\FactoryOrganizer;

class User extends Export implements SettingsInterface, SmUserInterface
{
    /**
     * @param $userProperties
     * @throws UserAccessException
     * @return mixed
     */
    public function getUserSettings($userProperties)
    {
        return $this->getDataCoreConfig();
    }

    public function getUserToken($userProperties)
    {
        $userData = $this->getDataCoreConfig();
        $status = (strlen($this->getToken()) == 64) ? true : false;

        $refresh = (time() > $this->getExpiresTokenAt()) ? true : false;

        if (isset($userData['properties'])) {
            $userData['properties'] = array_merge($userData['properties'], ['success' => true]);
        }

        $data = [
            'success'       => $status,
            Settings::TOKEN => $this->getToken(),
            'refresh'       => $refresh,
            'properties'    => isset($userData['properties']) ? $userData['properties'] : ''
        ];
        return $data;
    }

    public function refreshUserToken($userProperties)
    {
        if (isset($userProperties['token']) && !empty($userProperties['token'])) {
            $this
                ->setExpiresTokenAt()
                ->setUpdatedAtTime()
                ->setToken($userProperties['token']);
        } else {
            $this
                ->setExpiresTokenAt()
                ->setUpdatedAtTime();
        }
    }

    public function setCustomProperties($userProperties)
    {
        $this
            ->addUpdatedAtTime()
            ->extendValue(
                ['properties' => $userProperties]
            );
    }

    public function getDataForAccountType($userProperties)
    {
        $uData = $this->getUserSettings(null);

        return [
            'token' => $uData['token'],
            'email' => $uData['owner']
        ];
    }
}
