<?php

class iCalContactList extends PhonalisaRecord
{

    public $id;
    public $owner;
    public $thirdPartyCredentialId;
    public $provider;
    public $calendarId;
    public $iCalDirectoryPath;
    public $calendarDirectoryBasePath;
    public $calendarCTag;
    public $timestampLastSync;
    public $lastICloudImage;
    public $currentICloudImage;
    public $lastUploadList;
    public $downloadList;
    public $deletedICalContacts;
    public $uploadList;
    public $deletedLocalContacts;

    public static function myAttributes()
    {
        return array(
            'owner' => 'owner',
            'thirdPartyCredentialId' => 'thirdPartyCredentialId',
            'provider' => 'provider',
            'calendarId' => 'calendarId',
            'iCalDirectoryPath' => 'iCalDirectoryPath',
            'calendarDirectoryBasePath' => 'calendarDirectoryBasePath',
            'calendarCTag' => 'calendarCTag',
            'timestampLastSync' => 'timestampLastSync',
            'lastICloudImage' => 'lastICloudImage',
            'currentICloudImage' => 'currentICloudImage',
            'lastUploadList' => 'lastUploadList',
            'downloadList' => 'downloadList',
            'deletedICalContacts' => 'deletedICalContacts',
            'uploadList' => 'uploadList',
            'deletedLocalContacts' => 'deletedLocalContacts',
        );
    }

    /**
     * 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('owner, '
                . 'thirdPartyCredentialId, '
                . 'provider, '
                . 'addressBookId, '
                . 'calendarId, '
                . 'iCalDirectoryPath,'
                . 'calendarDirectoryBasePath,'
                . 'calendarCTag,'
                . 'timestampLastSync,'
                . 'lastICloudImage, '
                . 'currentICloudImage,'
                . 'lastUploadList,'
                . 'downloadList,'
                . 'deletedICalContacts,'
                . 'uploadList,'
                . 'deletedLocalContacts', 'safe'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array();
    }

    /**
     * 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 static function getICalRelevantAttributes()
    {
        return array('contact_tid', 'n_family', 'n_given', 'n_middle', 'n_prefix', 'n_suffix', 'n_fn', 'org_name',
            'org_unit', 'contact_email', 'contact_email_home', 'adr_one_street', 'adr_one_locality', 'adr_one_region',
            'adr_one_postalcode', 'adr_one_countryname', 'adr_two_street', 'adr_two_locality', 'adr_two_region',
            'adr_two_postalcode', 'adr_two_countryname', 'tel_cell_private', 'tel_cell', 'tel_work', 'tel_home',
            'tel_fax_home', 'tel_fax', 'twitter_profile_url', 'linkedin_profile_url', 'facebook_profile_url',
            'contact_note', 'contact_url_home', 'contact_url', 'contact_role'
        );
    }

    public function returnTimestamp($date)
    {
        $serverTimeZone = new DateTimeZone('GMT');
        $timestamp = new DateTime($date, $serverTimeZone);

        return $timestamp->format('U');
    }

    public function updateICalContactsList($listKey, $elementID)
    {
        $list = json_decode($this->$listKey, true);

        if (is_array($list)) {
            if (!array_key_exists($elementID, $list)) {
                $list[] = $elementID;
            }
        } else {
            $list[] = $elementID;
        }

        $this->$listKey = json_encode($list);

        if (!$this->save()) {
            $this->createErrorLogMessages($this);
        }
    }

    public function startICalSync()
    {
        $job = new Job();
        $job->type = Job::AddressImport;
        $job->user_id = $this->owner;
        $job->meta = json_encode(array(
            "limit" => 5,
            "offset" => 0,
            "thirdPartyCredentialId" => $this->thirdPartyCredentialId,
            "totalItemCount" => $this->findGreatestNumberOfListElements(),
            "progress" => 0,
        ));

        if (!$job->save()) {
            $this->createErrorLogMessages($job);
        }
    }

    public function findGreatestNumberOfListElements()
    {
        $downloadListCount = count(json_decode($this->downloadList, true));
        $deletedICalContactsCount = count(json_decode($this->deletedICalContacts, true));
        $uploadListCount = count(json_decode($this->uploadList, true));
        $deletedLocalContactsCount = count(json_decode($this->deletedLocalContacts, true));
        $items = array($downloadListCount, $deletedICalContactsCount, $uploadListCount, $deletedLocalContactsCount);

        return max($items);
    }

    private function createErrorLogMessages($model)
    {
        Log::e("An error has occurred saving " . get_class($model) . "-ID $model->id", 'iCalSync [iCalContactsList]');
        foreach ($model->errors as $key => $errorMsg) {
            Log::e("Error in $key ");
            if (is_array($errorMsg)) {
                Log::e("ErrorMessage in " . array_shift($errorMsg));
            }
        }
    }
}
