<?php

class PhonalisaInitializer
{

    private $defaultAdmin = null;
    private $dataBaseVersion = null;

    private function createDefaultGroups()
    {
        $allUsers = Groups::model()->findByAttributes(array('type' => 'allUsers'));
        if ($allUsers == null) {
            $allUsers = new Groups;
            $allUsers->type = 'allUsers';
            $allUsers->name = __("ALL_USERS_STANDARD_NAME");
            $allUsers->title = __("ALL_USERS_STANDARD_TITLE");
            $allUsers->parent = '0';

            if (!$allUsers->save()) {
                return false;
            }
        }
        return $allUsers;
    }

    private function createDefaultPermissions($groupId, $forwardSetId)
    {
        //FIXME add Permissions for all users and admin on intern addressbook
        include(__DIR__ . "/../modules/adminGroups/models/Permissions.php");
        $internAddressBook = Addressbook::model()->findByAttributes(array('type' => '3'));

        $permission = new Permissions;
        $permission->groupId = $groupId;
        $permission->type = 'read';
        $permission->itemId = $internAddressBook->id;
        if (!$permission->save()) {
            return false;
        }

        $permission = new Permissions;
        $permission->groupId = $groupId;
        $permission->type = 'read_forwardingset';
        $permission->itemId = $forwardSetId;
        if (!$permission->save()) {
            return false;
        }
        return true;
    }

    private function createDefaultWebGuiPermissions($groupId)
    {
        include(__DIR__ . "/../modules/adminWebGuiPermissions/models/WebGuiPermissions.php");
        $defaultPerimssions = new WebGuiPermissions;
        $defaultPerimssions->groupId = $groupId;
        $defaultPerimssions->permissions = json_encode($this->getDefaultSections());

        if (!$defaultPerimssions->save()) {
            return false;
        }
        return true;
    }

    private function createDefaultCallForwardingPreset()
    {
        $defaultCallForwardingPreset = new ForwardPreset();
        $defaultCallForwardingPreset->forwardType = ForwardType::Disabled;
        $defaultCallForwardingPreset->name = __("PHONALISA_INITIALIZER_DEFAULT_CALL_FORWARDING_SET_NAME");
        $defaultCallForwardingPreset->type = ForwardPresetType::PublicPreset;
        if ($defaultCallForwardingPreset->save()) {
            return $defaultCallForwardingPreset;
        }
        return false;
    }

    private function getDefaultSections()
    {
        $allModules = ModuleManager::getDeclaredModules();
        $defaultModules = array();
        $defaultMainSections = array('home');
        $defaultMainSections[] = 'analytics';
        $defaultMainSections[] = 'phonesettings';

        foreach ($allModules as $name => $module) {
            if (!in_array($name, $defaultMainSections)) {
                if (isset($module['section']) && in_array($module['section'], $defaultMainSections)) {
                    $defaultModules[$name] = '1';
                }
            }
        }
        return $defaultModules;
    }

    private function setDefaultAdminUser($user)
    {
        $this->defaultAdmin = $user;
    }

    public function getDefaultAdminUser()
    {
        return $this->defaultAdmin;
    }

    private function setDbVersion($version)
    {
        $dbVersion = new DatabaseVersion;
        $dbVersion->version = $version;
        if ($dbVersion->save()) {
            return true;
        } else {
            return false;
        }
    }

    public function createDataBaseVersionOne()
    {
        $addressBook = $this->createDefaultAddressbook();
        if (!$addressBook) {
            die('could not create Intern Addressbook');
        }

        $rootGroup = $this->createDefaultGroups();
        if (!$rootGroup) {
            die('could not create root group');
        }

        $defaultCallForwardingPreset = $this->createDefaultCallForwardingPreset();
        if (!$defaultCallForwardingPreset) {
            die('could not create default ForwardSet');
        }

        $admin = $this->createDefaultAdmin($rootGroup->id);
        if (!$admin) {
            die('could not create Admin user');
        }

        $defaultWebPermissions = $this->createDefaultWebGuiPermissions($rootGroup->id);
        if (!$defaultWebPermissions) {
            die('could not create default WebGuiPermissions');
        }

        $defaultPermissions = $this->createDefaultPermissions($rootGroup->id, $defaultCallForwardingPreset->id);
        if (!$defaultPermissions) {
            die('could not create default Permissions');
        }

        $dbVersion = $this->setDbVersion('1');
        if (!$dbVersion) {
            die('could not create DB version');
        }

        if (app()->params->applianceMode) {
            $defaultFirewallRules = $this->createDefaultFirewallRules();
            if (!$defaultFirewallRules) {
                die('could not create Firewall-rules');
            }

            $this->setAutoUpdateCronRule();
        }

        $this->setAutoCleanupCronRule();
        $this->setAutoCallProtectionCronRule();
        $this->setTapiMultiUserAuthtoken();
        $this->setCallServiceAuthtoken();
        $this->setCdrExportAuthtoken();
    }

    public function runInit()
    {
        $dbVersion = DatabaseVersion::model()->findAll(array('version' => $this->dataBaseVersion));
        if (!$dbVersion) {
            $this->createDataBaseVersionOne();
        }
        return true;
    }

    private function createDefaultAddressbook()
    {
        include(__DIR__ . "/../models/Addressbook.php");
        $book = Addressbook::model()->findByAttributes(array("type" => "3"));
        if ($book == NULL) {

            $book = new Addressbook;
            $book->icon = "adminGroups.png";
            $book->type = '3';
            $book->title = __("INTERNAL");

            if (!$book->save()) {
                return false;
            }
        }
        return $book;
    }

    private function createDefaultAdmin($groupId)
    {
        Yii::log("No user in database! creating admin/admin", "warning", "auth");
        $user = new User('firstUser');
        $user->group = $groupId;
        $user->isSystemAdmin = '1';

        if (!$user->save(false)) {
            return false;
        }
        $this->setDefaultAdminUser($user);
        return $user;
    }

    public static function addDefaultMohFiles()
    {
        Yii::import("application.modules.systemMusicOnHold.models.*");
        Yii::import("application.models.*");

        $directory = __DIR__ . "/../wizard/files/systemMusicOnHold";

        $moh = new MusicOnHold;
        $moh->name = __("DEFAULT_MOH_PLAYLIST_NAME");
        $moh->descr = __("DEFAULT_MOH_PLAYLIST_DESCRIPTION");

        $moh->save();

        foreach (new DirectoryIterator($directory) as $fileInfo) {
            if ($fileInfo->isDot())
                continue;

            $path_parts = pathinfo($fileInfo->getFilename());

            if ($path_parts['extension'] != 'wav') {
                continue;
            }

            $audioFile = new AudioFile;
            $audioFile->name = $path_parts['filename'];
            $audioFile->playlistID = $moh->id;
            $audioFile->fileName = $fileInfo->getFilename();
            $audioFile->type = AudioFileType::musicOnHold;
            $audioFile->save();

            $audioFile->saveFileToFieldByPath("data", $directory . '/' . $fileInfo->getFilename());
        }
    }

    private function createDefaultFirewallRules()
    {
        setCfg('FIREWALL_ENABLED', '1');
        $defaultRules = FirewallRule::getFirewallDefaultRules();
        foreach ($defaultRules as $key => $defaultRule) {
            $model = new FirewallRule();
            $model->attributes = $defaultRule;
            $model->chain = FirewallRule::CHAIN_INPUT;
            $model->sort = $key;
            if (!$model->save(false)) {
                return false;
            }
        }
        return true;
    }

    private function setAutoUpdateCronRule()
    {
        $cronRule = mt_rand(0, 59) . " 2 * * *";
        setCfg('UPDATE_CRON_JOB', $cronRule);
    }

    private function setAutoCleanupCronRule()
    {
        setCfg('CLEANUP_CRON_JOB', "0 1 * * *");
    }

    private function setAutoCallProtectionCronRule()
    {
        $cronRule = mt_rand(0, 59) . " 22 * * *";
        setCfg('CALL_PROTECTION_CRON_JOB', $cronRule);
    }

    private function setTapiMultiUserAuthtoken()
    {
        setCfg('TAPI_MULTI_USER_AUTHTOKEN', PasswordGenerator::generateToken());
    }

    private function setCallServiceAuthtoken()
    {
        setCfg('CALL_SERVICE_AUTHTOKEN', PasswordGenerator::generateToken());
    }

    private function setCdrExportAuthtoken()
    {
        setCfg('CDR_EXPORT_AUTHTOKEN', PasswordGenerator::generateToken());
    }
}
