<?php

namespace common\modules\testings\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

use common\modules\users\models\User;

class Passing extends \common\components\ActiveRecordModel
{
    const PAGE_SIZE = 10;

	const STARTED = 0;
	const PASSED = 1;
	const MISTAKE = 8;
    const FAILED = 9;

    const PASSING_PERCENT_RIGHT_CENTER = 50;
    const PASSING_PERCENT_RIGHT_ALMOST = 75;
    const PASSING_PERCENT_RIGHT_ALL = 100;

    public static $state_list = [
		self::STARTED => 'Начал тестирование',
        self::FAILED => 'Не сдал',
		self::PASSED => 'Сдал',
		self::MISTAKE => 'Ошибка',
    ];

    public static $answer_list = [
        self::STARTED => 'Не верно',
		self::PASSED => 'Верно',
    ];

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


    public function name()
    {
        return 'Прохождения';
    }

	/**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
        ];
    }

    public function rules()
	{
		return [
			[['user_id', 'test_id'], 'required'],
			[['user_id', 'test_id', 'is_passed'], 'integer'],
			[['pass_date', 'pass_date_start', 'attempt'], 'safe'],
			[['end_date'], 'required', 'on' => 'extend'],
		];
	}

	public function attributeLabels() 
	{
		return [
			'is_passed' => 'Состояние',
			'test_id' => 'Tест',
			'user_id' => 'ФИО',
			'create_date' => 'Дата создания',
			'pass_date' => 'Дата прохождения теста',
			'session_id' => 'Сессия',
			'filter_user_email' => 'Email',
			'filter_user_company_name' => 'Наименование компании',
			'filter_user_last_name' => 'ФИО',
		];
	}

	public function getMistake()
    {
        return $this->hasOne(Mistake::className(), ['passing_id' => 'id']);
    }

    public function getTest()
    {
        return $this->hasOne(Test::className(), ['id' => 'test_id']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getQuestions()
    {
        return $this->hasMany(QuestionPassing::className(), ['passing_id' => 'id']);
    }

    public function getCountPassedQuestions() 
    {
        $count = 0;

        foreach($this->questions as $question) 
        {
            if($question->isRight) 
            {
                $count++;
            }
        }

        return $count;
    }

	public function getPercent() 
	{
		$all = 0;
		$right = 0;

		foreach ($this->questions as $pq) 
		{
			$all++;
			if ($pq->isRight) 
			{
				$right++;
			}
		}

		return ($all <> 0) ? ceil($right*100/$all) : "- ";
	}

	public function getPercentStep() 
	{
		return ceil(($this->percent * 100) / $this->test->pass_percent);
	}

	public function getMessageStep()
	{
		$list = [
			self::PASSING_PERCENT_RIGHT_ALL => Settings::getValue('message_passing_percent_right_all'),
	        self::PASSING_PERCENT_RIGHT_ALMOST => Settings::getValue('message_passing_percent_right_almost'),
			self::PASSING_PERCENT_RIGHT_CENTER => Settings::getValue('message_passing_percent_right_center'),
	    ];

	    foreach ($list as $percent => $message) 
	    {
	    	if($this->percentStep >= $percent)
		    {
		    	return array('message' => $list[$percent], 'percent' => $percent);
		    }
	    }
	    
	    return;
	}

	public function getTime() 
	{
		if($this->pass_date_start && $this->pass_date)
		{
			return (strtotime($this->pass_date) - strtotime($this->pass_date_start));
		}
		else
		{
			$timeSummary = 0;
			foreach ($this->questions as $q) {
				$timeSummary += $q->answer_time;
			}
			return $timeSummary;
		}
	}

	public static function declOfNum($number, $titles)
	{
	    $cases = array (2, 0, 1, 1, 1, 2);
	    return $number." ".$titles[ ($number%100 > 4 && $number %100 < 20) ? 2 : $cases[min($number%10, 5)] ];
	}
}
