<?php

namespace common\modules\languages\controllers\manage;

use common\modules\languages\entities\Language;
use common\modules\languages\forms\LanguageForm;
use common\modules\languages\forms\search\LanguageSearch;
use common\modules\languages\services\LanguageManageService;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use Yii;

class LanguageController extends Controller
{
    private $service;

    public function __construct($id, $module, LanguageManageService $service, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->service = $service;
    }

    public function behaviors(): array
    {
        return [
	        'access' => [
		        'class' => AccessControl::class,
		        'rules' => [
			        [
				        'allow' => true,
				        'roles' => ['LanguagesManagement'],
			        ],
			        [    // all the action are accessible to admin
				        'allow' => true,
				        'roles' => ['admin'],
			        ],
		        ],
	        ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                    'set-default' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new LanguageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

	/**
	 * @param $id
	 *
	 * @return string
	 * @throws NotFoundHttpException
	 */
    public function actionView($id)
    {
        return $this->render('view', [
            'language' => $this->findModel($id),
        ]);
    }

    /**
     * @return mixed
     */
    public function actionCreate()
    {
        $form = new LanguageForm();

        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            try {
                $form = $this->service->create($form);
                return $this->redirect(['view', 'id' => $form->id]);
            } catch (\DomainException $e) {
                Yii::$app->errorHandler->logException($e);
                Yii::$app->session->setFlash('error', $e->getMessage());
            }
        }
        else {
	        $form->status = $form->status ?: Language::STATUS_ACTIVE;
        }
        return $this->render('create', [
            'model' => $form,
        ]);
    }

	/**
	 * @param $id
	 *
	 * @return string|\yii\web\Response
	 * @throws NotFoundHttpException
	 */
    public function actionUpdate($id)
    {
        $language = $this->findModel($id);
        $form = new LanguageForm($language);

        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            try {
                $this->service->edit($language->id, $form);
                return $this->redirect(['view', 'id' => $language->id]);
            } catch (\DomainException $e) {
                Yii::$app->errorHandler->logException($e);
                Yii::$app->session->setFlash('error', $e->getMessage());
            }
        }

        return $this->render('update', [
            'model' => $form,
            'language' => $language,
        ]);
    }

    /**
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        try {
            $this->service->remove($id);
        } catch (\DomainException $e) {
            Yii::$app->errorHandler->logException($e);
            Yii::$app->session->setFlash('error', $e->getMessage());
        }
        return $this->redirect(['index']);
    }

    public function actionSetDefault($id)
    {
		$language = $this->findModel($id);
		if ($language) {
			$this->service->setDefault($language);
			return $this->redirect(['index']);
		}
	    throw new NotFoundHttpException('Language is not exists');
    }

    /**
     * @param integer $id
     * @return Language the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id): Language
    {
        if (($model = Language::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested language does not exist.');
    }
}