<?php
namespace common\modules\eauth\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use common\modules\users\models\User;
use common\modules\rbac\models\AuthAssignment; 

class UserEAuth extends \common\components\ActiveRecordModel
{
    public $created_at;
    public $updated_at;

	public function attributeLabels()
	{
		$attrs = array_merge(parent::attributeLabels(), array(
			"id"   => "ID",
		));
		
		return $attrs;
	}

	public function rules()
	{
		return [
			[['user_id'], 'required'],
            [['google_id', 'twitter_id', 'vk_id', 'facebook_id'], 'integer','integerOnly' => true],
		];
	}

    public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}


	public static function tableName()
	{
		return 'users_eauth';
	}


	public function name()
	{
		return "Социальные аккаунты пользователя";
	}
    
    public static function findById($id)
    {
        return static::findOne(['id' => $id]);
    }
	
    /**
     * Finds user by user id
     *
     * @param string $user_id
     * @return static|null
     */
    public static function findByUserId($user_id)
    {
        return static::findOne(['user_id' => $user_id]);
    }

	public function relations()
	{
		return array(
            'user' => array(self::BELONGS_TO, 'User', 'user_id')
		);
	}

    /**
     * @param \nodge\eauth\ServiceBase $service
     * @return User
     * @throws ErrorException
     */
    public function getByEAuth($service) {
        /*if (!$service->getIsAuthenticated()) {
            throw new ErrorException('EAuth user should be authenticated before creating identity.');
        }*/

        $userModel = new User();
        $socialProfile = $service->getSocialProfile();
        $eauthField = $service->getServiceName().'_id';

        // Check is User EAuth service token exists
        if ($this->isEAuthExists($service)) {
            // Get existing user model
            return $userModel->getByEAuth($service);
        }
        // Check is User with such email exists - assign Eauth token to him
        elseif ($userModel->isUserEmailExists($socialProfile['email'])) {
            $model = User::findByUsername($socialProfile['email']);

            // Assign service token
            $modelEAuth = $model->eauth ? $model->eauth : new UserEauth();
            $modelEAuth->user_id = $model->id;
            $modelEAuth->{$eauthField} = $socialProfile['id'];
            $modelEAuth->update(false, [$eauthField]);

            return $model;
        }
        else {
            // Create and save new user
            $model = new User();
            $model->scenario = User::SCENARIO_SOCIAL_REGISTRATION;
            $model->email = $socialProfile['email'];
            $model->name = $socialProfile['name'];
            $model->status = User::STATUS_ACTIVE;
            $model->activate_date = date('Y-m-d H:i:s');
            $model->source = User::SOURCE_DEFAULT;
            
            if ($model->save()) {
                // Assign role
                $assignment = new AuthAssignment();
                $assignment->item_name = 'user';
                $assignment->user_id = $model->id;
                $assignment->save();

                // Assign EAuth data
                $eauth = new UserEAuth();
                $eauth->user_id = $model->id;
                $eauth->{$eauthField} = $socialProfile['id'];
                $eauth->save();
                return $model;
            }
            else {
                echo '<pre>'; die(var_dump($model->getErrors())); echo '</pre>';
            }

            return false;
        }

        /*$id = $service->getServiceName().'-'.$service->getId();
        $attributes = [
            'id' => $id,
            'username' => $service->getAttribute('name'),
            'authKey' => md5($id),
            'profile' => $service->getAttributes(),
        ];
        $attributes['profile']['service'] = $service->getServiceName();
        Yii::$app->getSession()->set('user-'.$id, $attributes);*/
    }

    public function isEAuthExists($service)
    {
        $socialProfile = $service->getSocialProfile();
        $eauthField = $service->getServiceName().'_id';

        return (bool)static::find()->where($eauthField.' = :eauth', [':eauth'=>$socialProfile['id']])->count();
    }
}

