<?php

namespace humhub\modules\cgyshare\models;

use humhub\modules\space\models\Space;
use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;

class ConfigureForm extends Model
{
    public $targetSpaceGuid;
    public $publicOnly = 1;
    public $autoShareEnabled = 1;

    public function rules()
    {
        return [
            [['targetSpaceGuid'], 'required'],
            [['targetSpaceGuid'], 'string'],
            [['publicOnly', 'autoShareEnabled'], 'boolean'],
            ['targetSpaceGuid', 'validateSpace'],
        ];
    }

    public function validateSpace($attribute)
    {
        if (!Space::findOne(['guid' => $this->$attribute])) {
            $this->addError($attribute, 'Please select a valid Space.');
        }
    }

    public function attributeLabels()
    {
        return [
            'targetSpaceGuid' => 'Main Space',
            'publicOnly' => 'Allow public posts only',
            'autoShareEnabled' => 'Automatically share profile posts to the Main Space',
        ];
    }

    public function loadSettings()
    {
        $module = Yii::$app->getModule('cgy-share');
        $settings = $module->settings;

        $this->targetSpaceGuid = $settings->get('targetSpaceGuid');
        $this->publicOnly = (int)$settings->get('publicOnly', 1);
        $this->autoShareEnabled = (int)$settings->get('autoShareEnabled', 1);
    }

    public function saveSettings()
    {
        $module = Yii::$app->getModule('cgy-share');
        $module->settings->set('targetSpaceGuid', $this->targetSpaceGuid);
        $module->settings->set('publicOnly', (int)$this->publicOnly);
        $module->settings->set('autoShareEnabled', (int)$this->autoShareEnabled);
        return true;
    }

    public function getSpaceOptions()
    {
        return ArrayHelper::map(
            Space::find()->orderBy(['name' => SORT_ASC])->all(),
            'guid',
            'name'
        );
    }
}
