<?php

class ThirdPartyProvider
{

    const XING = 'XING';
    const ICLOUD = 'iCloud';
    const GOOGLE = 'Google';

}

class ThirdPartyCredentialStatus
{

    const valid = '1';
    const invalid = '0';
    const authenticated = '1';
    const notAuthenticated = '0';

}

class iCloudTypes
{

    const contacts = "contacts";
    const calendars = "calendars";

}

class ThirdPartyCredential extends PhonalisaRecord
{

    public $id;
    public $owner;
    public $title;
    public $provider;
    public $token;
    public $secret;
    public $updated;
    public $authenticated = ThirdPartyCredentialStatus::notAuthenticated;
    public $hauthSession;
    public $addressBookId;
    public $calendarId;
    public $serverURI;
    public $addressBookURI;
    public $username;
    public $password;
    public $iCloudCalendars;
    public $newCalendarText;
    public $newCalendarCheckBox;
    public $addressBookCheckBox;
    public $calendarCheckBox;
    public $syncCalendars;
    public $passwordStatus;
    public $newPassword;
    public $confirmPassword;
    public $validate;

    public static function myAttributes()
    {

        return array(
            'owner' => 'owner',
            'provider' => 'provider',
            'title' => 'title',
            'token' => 'token',
            'secret' => 'secret',
            'updated' => 'updated',
            'authenticated' => 'authenticated',
            'hauthSession' => 'hauthSession',
            'addressBookId' => 'addressBookId',
            'calendarId' => 'calendarId',
            'serverURI' => 'serverURI',
            'addressBookURI' => 'addressBookURI',
            'username' => 'username',
            'password' => 'password',
            'iCloudCalendars' => 'iCloudCalendars',
            'newCalendarText' => 'newCalendarText',
            'newCalendarCheckBox' => 'newCalendarCheckBox',
            'addressBookCheckBox' => 'addressBookCheckBox',
            'calendarCheckBox' => 'calendarCheckBox',
            'syncCalendars' => 'syncCalendars',
            'passwordStatus' => 'passwordStatus',
            'newPassword' => 'newPassword',
            'confirmPassword' => 'confirmPassword',
            'validate' => 'validate',
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return RoutingInbound the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('provider, addressBookId', 'required', 'on' => 'XING'),
            array('provider, addressBookId', 'required', 'on' => 'Google'),
            array('provider, username, password', 'required', 'on' => 'iCloud'),
            array('serverURI', 'required', 'on' => 'iCloud', 'message' => __('THIRDPARTYCREDENTIAL_ICLOUD_CLIENT_ERROR_INVALID_USER_PWD')),
            array('validate', 'required', 'on' => 'iCloud', 'message' => __('THIRDPARTYCREDENTIAL_MODEL_ICLOUD_SAVE_ERROR')),
            array('provider, addressBookId, calendarId, iCloudCalendars, syncCalendars', 'safe'),
            array(
                'owner, '
                . 'provider, '
                . 'title, '
                . 'token, '
                . 'secret, '
                . 'updated, '
                . 'authenticated, '
                . 'hauthSession, '
                . 'addressBookId, '
                . 'calendarId, '
                . 'serverURI'
                . 'addressBookURI'
                . 'username'
                . 'password'
                . 'iCloudCalendars'
                . 'newCalendarText'
                . 'newCalendarCheckBox'
                . 'addressBookCheckBox'
                . 'calendarCheckBox'
                . 'synCalendars'
                . 'serverURI, '
                . 'username, '
                . 'password, '
                . 'passwordStatus',
                'safe',
                'on' => 'update'
            ),
            array('username', 'email', 'on' => 'iCloud'),
            array('title', 'length', 'max' => 128),
            array('newPassword, confirmPassword', 'required', 'on' => 'changePassword'),
            array('serverURI', 'required', 'on' => 'changePassword', 'message' => __('THIRDPARTYCREDENTIAL_ICLOUD_CLIENT_ERROR_INVALID_PASSWORD')),
            array('confirmPassword', 'compare', 'compareAttribute' => 'newPassword', 'message' => __('THIRDPARTYCREDENTIAL_MODEL_PASSWORD_REPEAT_ERROR_MESSAGE'))
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'provider' => __('THIRDPARTYCREDENTIAL_MODEL_PROVIDER'),
            'title' => __('THIRDPARTYCREDENTIAL_MODEL_TITLE'),
            'authenticated' => __('THIRDPARTYCREDENTIAL_MODEL_TITLE_AUTHENTICATED'),
            'token' => __('THIRDPARTYCREDENTIAL_MODEL_TOKEN'),
            'secret' => __('THIRDPARTYCREDENTIAL_MODEL_SECRET'),
            'owner' => __('THIRDPARTYCREDENTIAL_MODEL_OWNER'),
            'updated' => __('THIRDPARTYCREDENTIAL_MODEL_UPDATED'),
            'hauthSession' => __('THIRDPARTYCREDENTIAL_MODEL_HAUTH_SESSION'),
            'addressBookId' => __('THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_ID'),
            'calendarId' => __('THIRDPARTYCREDENTIAL_MODEL_CALENDAR_ID'),
            'providerIcon' => __('THIRDPARTYCREDENTIAL_MODEL_PROVIDER_ICON'),
            'addressBookName' => __('THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_NAME'),
            'calendarName' => __('THIRDPARTYCREDENTIAL_MODEL_CALENDAR_NAME'),
            'serverURI' => __('THIRDPARTYCREDENTIAL_MODEL_SERVERURI'),
            'username' => __('THIRDPARTYCREDENTIAL_MODEL_USERNAME'),
            'password' => __('THIRDPARTYCREDENTIAL_MODEL_PASSWORD'),
            'iCloudCalendars' => __('THIRDPARTYCREDENTIAL_MODEL_ICLOUD_CALENDAR_ID'),
            'newCalendarText' => __('THIRDPARTYCREDENTIAL_MODEL_NEW_CALENDAR'),
            'newCalendarCheckBox' => __('THIRDPARTYCREDENTIAL_MODEL_NEW_CALENDAR_NAME'),
            'addressBookCheckBox' => __('THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_CHECKBOX'),
            'calendarCheckBox' => __('THIRDPARTYCREDENTIAL_MODEL_CALENDAR_CHECKBOX'),
            'passwordStatus' => __('THIRDPARTYCREDENTIAL_MODEL_TITLE_PASSWORD_STATUS'),
            'newPassword' => __('THIRDPARTYCREDENTIAL_MODEL_NEW_PASSWORD'),
            'confirmPassword' => __('THIRDPARTYCREDENTIAL_MODEL_CONFIRM_PASSWORD')
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CPhonalisaDataProvider the data provider
     * that can return the models based on the search/filter conditions.
     */
    public function search($order = 'title')
    {
        $criteria = new CDbCriteria;
        $criteria->condition = 'owner=' . Yii::app()->user->sudoUser;

        $dataProvider = new CPhonalisaDataProvider($this, array(
            'criteria' => $criteria,
        ));
        return $dataProvider;
    }

    public function modalSearch($thirdPartyId, $order = 'id')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $models = $this->findAllByAttributes(array('id' => $thirdPartyId));
        if (empty($models)) {
            $models[] = $this;
        }
        return new CArrayDataProvider($models, array('pagination' => false));
    }

    public function hasRunningJob()
    {
        $jobs = Job::model()->findAllByAttributes(array(
            "type" => Job::AddressImport,
            "user_id" => app()->user->sudoUser,
            "status" => Job::Running
        ));
        foreach ($jobs as $job) {
            $meta = json_decode($job->meta);
            if ($this->id == $meta->thirdPartyCredentialId) {
                return true;
            }
        }
        return false;
    }

    public function enabledProviders()
    {
        return array(
//            ThirdPartyProvider::XING => ThirdPartyProvider::XING,
            ThirdPartyProvider::ICLOUD => ThirdPartyProvider::ICLOUD,
           // ThirdPartyProvider::GOOGLE => ThirdPartyProvider::GOOGLE
        );
    }

    public function getAddressBookName()
    {
        $addressBook = Addressbook::model()->findByPk($this->addressBookId);

        if ($addressBook != null) {
            return $addressBook->title;
        }
        return 'n/a';
    }

    public function getCalendarName()
    {
        $calendars = json_decode($this->syncCalendars, true);
        if (is_array($calendars)) {
            $calendar = "|";

            foreach ($calendars as $calendarIDs) {
                $id = current($calendarIDs);
                $calendarModel = Calendar::model()->findByPk($id);
                if ($calendarModel) {
                    $calendar = $calendar . " " . $calendarModel->title . " |";
                }
            }

            if ($calendar != null && $calendar != "|") {
                return $calendar;
            }
        }
        return 'n/a';
    }

    public function beforeSave()
    {
        if (empty($this->owner)) {
            $this->owner = Yii::app()->User->sudoUser;
        }
        $this->updated = time();
        return parent::beforeSave();
    }

    public function beforeDelete()
    {
        $contactLists = iCloudContactsList::model()->findAllByAttributes(array('thirdPartyCredentialId' => $this->id));
        foreach ($contactLists as $contactList) {
            if (!$contactList->delete()) {
                Log::e('An error has occurred deleting ' . get_class($contactList) . ' ID-' . $contactList->id, 'ThirdPartyCredential');
                return false;
            }
        }
        return parent::beforeDelete();
    }
}
