<?php

class UserTest extends ModelTest
{

    private $internAddressId = null;
    private $secretaryId = null;
    private $allUsersGroupId = null;
    private $extNumberId = null;

    public function __construct()
    {
        parent::__construct();
        Yii::import('adminUsers.models.*');
        Yii::import('adminGroups.models.*');
        Yii::import('adminWebGuiPermissions.models.*');
    }

    public function testDeleteLastAdmin()
    {
        $this->model->attributes = $this->getAttributeValues();
        $this->model->isSystemAdmin = "1";
        $this->model->extension = (int) $this->model->extension + 1;
        $this->model->name = "superzerg";
        $this->model->validate();
        $this->model->save();
        try {
            $this->assertFalse($this->model->delete());
        } catch (Exception $e) {
            $e->getMessage();
            $this->assertTrue($e->getMessage() == __('USER_MODEL_ERROR_MESSAGE_CANT_DELETE_LAST_ADMIN'));
            $this->model->isSystemAdmin = "0";

            $this->removeWelcomeMails();
            $this->model->scenario = "update";

            $this->model->save(false);
            $this->removeWelcomeMails();

            $this->assertTrue($this->model->delete());
        }
    }

    public function getAttributeValues()
    {
        $allUserGroup = Groups::model()->findByAttributes(array('type' => "allUsers"));
        if (!$allUserGroup) {
            $allUserGroup = $this->createAllUserGroup();
        }

        $attributes = array(
            "extension" => '698',
            "name" => 'zerg',
            "group" => $allUserGroup->id,
            "firstname" => 'Zerg',
            "lastname" => "Zimmermann",
            "email" => "zerg@example.com",
            "password" => $this->model->isNewRecord ? "demo" : $this->model->password,
            "pin" => "1234",
            "zrtp" => "0",
            "fax_header_text" => "Zerg Fax!",
            "fax_header_number" => "28364",
            "droptarget" => "777",
            'user_timezone' => '',
            'user_language' => '',
            'user_time_format' => '',
            'user_date_format' => '',
            'addressReferece' => '',
            'phone_presence' => '',
            'jabber_presence' => '',
            'jabber_presence_text' => '',
            'jabber_pw_digest' => $this->model->isNewRecord ? "demo" : $this->model->jabber_pw_digest,
            'clip_int' => '',
            'clip_ext' => '',
            'clir_int' => '',
            'clir_ext' => '',
            'call_waiting' => '',
            'dnd' => '',
            'email_fax' => '',
            'email_vmail' => '',
            'email_external_missed_call' => '',
            'key_tone' => '',
            'ringtone_int' => '',
            'ringtone_ext' => '',
            'ringtone_queue' => '',
            'email_vmail_delete' => '',
            'short' => '',
            'value' => '',
            'descr' => '',
            'type' => '',
            'key' => '',
            'userMonitor' => '',
            'activeCallForward' => '',
            'simpleCallForwardJson' => '',
            'advancedCallForwardJson' => '',
            'internMessageBeforeAnswer' => '',
            'externMessageBeforeAnswer' => '',
            'isSystemAdmin' => '0',
            'callForwardSet' => '',
            'defaultCallForwardSet' => '',
            'accountBalance' => ''
        );
        return $attributes;
    }

    public function beforeSaveTestRecord()
    {
        if (!$this->model->isNewRecord) {
            $this->model->unsetAttributes(array('password'));
            $oldExtension = $this->model->extension;
            $this->model->attributes = $this->getAttributeValues();

            $account = SipAccounts::model()->findByAttributes(
                array(
                    'user_id' => $this->model->id,
                    'authname' => $oldExtension
                )
            );

            if ($account) {
                $account->authname = $this->model->extension;
                $account->save();
            }

            $internAddress = Addresses::model()->findByPk($this->model->addressReferece);
            if (!$internAddress) {
                $this->model->addressReferece = $this->createInternAddress($this->model->attributes);
            }
        }
    }

    public function afterSaveTestRecord()
    {
        if (!$this->model->isNewRecord) {
            $this->assertTrue(
                $this->checkSipAccountExists(),
                "SipAccount was not created after save"
            );
            $this->assertTrue(
                $this->checkReferenceAddressExists(),
                "reference address was not created after save"
            );

            $this->saveSecretaries();
            $this->saveTiers();
            $this->saveExternalNumbers();
        } elseif ($this->model->email != "") {
            $this->assertTrue(
                $this->checkWelcomeMailExists(),
                "welcome mail was not created after save"
            );
        }
    }

    private function checkReferenceAddressExists()
    {
        $referenceAddress = Addresses::model()->findByPk($this->model->addressReferece);
        if ($referenceAddress) {
            return true;
        }
        return false;
    }

    private function checkSipAccountExists()
    {
        $sipaccount = SipAccounts::model()->findByAttributes(
            array(
                "authname" => $this->model->extension,
                "user_id" => $this->model->id
            )
        );
        if ($sipaccount) {
            return true;
        }
        return false;
    }

    private function checkWelcomeMailExists()
    {
        $email = UCItem::model()->findByAttributes(
            array(
                "owner_id" => $this->model->id,
                "typ" => "welcome_email"
            )
        );
        if ($email) {
            return true;
        }
        return false;
    }

    private function checkTiersExists()
    {

        $tiers = Tiers::model()->findByAttributes(
            array("userId" => $this->model->id)
        );
        if ($tiers) {
            return true;
        }
        return false;
    }

    public function beforeDeleteTestRecord()
    {
        $this->assertTrue(
            $this->checkReferenceAddressExists(),
            "reference address not exist."
        );
        $this->assertTrue(
            $this->checkSipAccountExists(),
            "sip account not exist."
        );
        $this->assertTrue(
            $this->checkTiersExists(),
            "tiers not exist."
        );
        $this->assertTrue(
            $this->checkSecretarysExists(),
            "secretary not exist."
        );
        $this->assertTrue(
            $this->checkExternalNumberExists(),
            "external number not exist."
        );
    }

    public function afterDeleteTestRecord()
    {
        $this->assertFalse(
            $this->checkReferenceAddressExists(),
            "can't delete reference address."
        );
        $this->assertFalse(
            $this->checkSipAccountExists(),
            "can't delete sip account."
        );
        $this->assertFalse(
            $this->checkTiersExists(),
            "can't delete tiers."
        );
        $this->assertFalse(
            $this->checkSecretarysExists(),
            "can't delete secretarys."
        );
        $this->assertFalse(
            $this->checkExternalNumberExists(),
            "can't delete external numbers."
        );

        //clear DB :
        $this->removeSecretaryUser();
        $this->removeTestQueue();
        $this->removeTestGroup();
        $this->removeTestAddressBook();
        $this->removeDeletedItem();
        $this->removeWelcomeMails();
        $this->removeTestAllUsersGroup();
        $this->removeDataBaseVersion();
    }

    // equal to adminUser/controllers/DefaultController createInternAddress()
    private function createInternAddress($newAttributes)
    {
        //creating intern addressbook enty for this user
        $internAddressbook = Addressbook::model()->findByAttributes(array('type' => AddressbookType::intern));

        if (!$internAddressbook) {
            $internAddressbook = $this->createInternAddressbook();
        }

        if ($internAddressbook) {

            $internAddress = new Addresses();
            $internAddress->n_given = $newAttributes['firstname'];
            $internAddress->n_family = $newAttributes['lastname'];
            $internAddress->contact_owner = 'intern';
            $internAddress->contact_email = $newAttributes['email'];
            $internAddress->contact_tid = $internAddressbook->id;
            $internAddress->tel_work = $newAttributes['extension'];
            $internAddress->source = AddressSourceType::SYSTEM;

            if (!$internAddress->save()) {
                print_r($internAddress->errors);
            } else {
                $this->internAddressId = $internAddress->id;
                return $internAddress->id;
            }
        }
    }

    private function saveSecretaries()
    {
        $secretaryUser = new User();
        $secretaryUser->attributes = $this->getAttributeValues();
        $secretaryUser->extension = "589";
        $secretaryUser->name = "secretary";
        if (!$secretaryUser->save()) {
            print_r($secretaryUser->errors);
        } else {
            $this->secretaryId = $secretaryUser->id;
        }

        $secretary = new Secretary();
        $secretary->bossId = $this->model->id;
        $secretary->secretaryId = $secretaryUser->id;
        $secretary->save();

    }

    private function checkSecretarysExists()
    {
        $secretary = Secretary::model()->findByAttributes(array('bossId' => $this->model->id));

        if ($secretary) {
            return true;
        }

        return false;
    }

    private function removeSecretaryUser()
    {
        $secraetaryUser = User::model()->findByAttributes(
            array("extension" => "589")
        );
        $secraetaryUser->delete();
    }

    private function saveTiers()
    {
        $queue = new Queue();
        $queue->name = "AdminUserTestQueue";
        $queue->extension = "489";
        $queue->save();

        $tier = new Tiers();
        $tier->userId = $this->model->id;
        $tier->queueId = $queue->id;
        $tier->level = 5;
        $tier->position = '4';
        $tier->type = TiersType::user;
        $tier->static_member = "0";
        $tier->loggedIn = "0";
        $tier->timeout = '10';
        $tier->save();
    }

    public function removeTestQueue()
    {
        $queue = Queue::model()->findByAttributes(array("extension" => "489"));
        if ($queue) {
            $queue->delete();
        }
    }

    private function createAllUserGroup()
    {
        $testGreoup = new Groups();
        $testGreoup->name = "allUsersTest";
        $testGreoup->type = "allUsers";
        $testGreoup->parent = "0";

        $testGreoup->save();
        $this->allUsersGroupId = $testGreoup->id;
        return $testGreoup;
    }

    private function removeTestGroup()
    {
        $testGreoup = null;
        $testGreoup = Groups::model()->findByAttributes(array('name' => "allUsersTest", "type" => "allUsers"));
        if ($testGreoup) {
            $testGreoup->delete();
        }
    }

    private function createInternAddressbook()
    {

        $internAddressbook = new Addressbook();
        $internAddressbook->icon = "adminGroups.png";
        $internAddressbook->type = '3';
        $internAddressbook->title = "internTestBook";
        $internAddressbook->save();
        return $internAddressbook;
    }

    private function removeTestAddressBook()
    {

        $testBook = Addressbook::model()->findByAttributes(
            array(
                "title" => "internTestBook",
                "type" => "3"
            )
        );

        if ($testBook) {
            $testBook->delete();
            return true;
        }
        return false;
    }

    private function removeDeletedItem()
    {
        $deletedItem = DeletedItem::model()->findByAttributes(array("model_id"=>$this->internAddressId));
        if ($deletedItem) {
            $deletedItem->delete();
        }
    }

    private function removeDataBaseVersion()
    {
        $dbversionHelper = DBVersionHelper::getInstance();
        if ($dbversionHelper->version->version == 1) {

            $dbversionHelper->version->delete();
        }
    }

    private function removeTestAllUsersGroup()
    {
        if ($this->allUsersGroupId) {
            $testGroup = Groups::model()->findByPk($this->allUsersGroupId);
            if ($testGroup) {
                $testGroup->delete();
            }
        }
    }

    private function removeWelcomeMails()
    {
        $userWelcomeMail = UCItem::model()->findByAttributes(
            array(
                "typ"=>"welcome_email",
                "owner_id"=>$this->model->id
            )
        );

        if ($userWelcomeMail) {
            $userWelcomeMail->delete();
        }

        $secretaryWelcomeMail = UCItem::model()->findByAttributes(
            array(
                "typ"=>"welcome_email",
                "owner_id"=>$this->secretaryId
            )
        );

        if ($secretaryWelcomeMail) {
            $secretaryWelcomeMail->delete();
        }

    }

    private function saveExternalNumbers()
    {
        $extNumber = new ExternalNumber();
        $extNumber->userId = $this->model->id;
        $extNumber->pattern = "*";
        if ($extNumber->save()) {
            $this->extNumberId = $extNumber->id;
        }
    }

    private function checkExternalNumberExists()
    {
        $extNumber = ExternalNumber::model()->findByAttributes(array('userId'=>$this->model->id));
        if (!$extNumber) {
            return false;
        }
        return true;
    }
}
