<?php

class iCloudContactsList extends PhonalisaRecord
{

    public $id;
    public $owner;
    public $thirdPartyCredentialId;
    public $iCloudType;
    public $plDirectoryId;
    public $iCloudDirectoryPath;
    public $directoryBasePath;
    public $cTag;
    public $timestampLastSync;
    public $lastICloudImage;
    public $currentICloudImage;
    public $lastUploadList;
    public $downloadList;
    public $deletedICloudContacts;
    public $uploadList;
    public $deletedLocalContacts;

    public static function myAttributes()
    {
        return array(
            'owner' => 'owner',
            'thirdPartyCredentialId' => 'thirdPartyCredentialId',
            'iCloudType' => 'iCloudType',
            'plDirectoryId' => 'plDirectoryId',
            'iCloudDirectoryPath' => 'iCloudDirectoryPath',
            'directoryBasePath' => 'directoryBasePath',
            'cTag' => 'cTag',
            'timestampLastSync' => 'timestampLastSync',
            'lastICloudImage' => 'lastICloudImage',
            'currentICloudImage' => 'currentICloudImage',
            'lastUploadList' => 'lastUploadList',
            'downloadList' => 'downloadList',
            'deletedICloudContacts' => 'deletedICloudContacts',
            '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, '
                . 'iCloudType, '
                . 'plDirectoryId, '
                . 'iCloudDirectoryPath,'
                . 'directoryBasePath,'
                . 'cTag,'
                . 'timestampLastSync,'
                . 'lastICloudImage, '
                . 'currentICloudImage,'
                . 'lastUploadList,'
                . 'downloadList,'
                . 'deletedICloudContacts,'
                . '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 getICloudRelevantAttributes()
    {
        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 updateICloudContactsList($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 deleteShiftedEventInOtherDirectory($iCloudData, $id)
    {
        require_once __DIR__ . '/../modules/phonesettingsThirdPartyCredentials/models/ThirdPartyCredential.php';
        require_once __DIR__ . '/../modules/phonesettingsThirdPartyCredentials/components/iCloudSync/iCloudClient.php';

        $thidPartyCredentials = ThirdPartyCredential::model()->findByPk($this->thirdPartyCredentialId);
        $uri = $this->iCloudDirectoryPath . $iCloudData->fileName;

        $iCloudClient = new iCloudClient($thidPartyCredentials->username, $thidPartyCredentials->password);
        $iCloudClient->executeRequest($uri, "DELETE", "Content-Type: urn:ietf:params:xml:ns:caldav'");

        $this->unsetShiftedEventInContactsList('lastICloudImage', $iCloudData->fileName, $id);
        $this->unsetShiftedEventInContactsList('currentICloudImage', $iCloudData->fileName, $id);
        $this->unsetShiftedEventInContactsList('lastUploadList', $iCloudData->fileName, $id);
    }

    private function unsetShiftedEventInContactsList($listKey, $shiftedEventName, $elementID)
    {
        $list = json_decode($this->$listKey, true);

        if (is_array($list)) {
            foreach ($list as $key => $entry) {
                if (!empty($entry['fileName']) && ($entry['fileName'] == $shiftedEventName || $entry['fileName'] == $elementID)) {
                    unset($list[$key]);
                }
            }
            if (array_key_exists($elementID, $list)) {
                unset($list[$elementID]);
            }
            if (array_key_exists($shiftedEventName, $list)) {
                unset($list[$shiftedEventName]);
            }
            if (empty($list)) {
                $list = array();
            }
        }

        $this->$listKey = json_encode($list);
        if (!$this->save()) {
            $this->createErrorLogMessages($this);
        }
    }

    public function startICloudSync()
    {
        if (!ThirdPartyCredential::model()->findByPk($this->thirdPartyCredentialId)) {
            Log::d("Can't find ThirdPartyCredential-model with ID '$this->thirdPartyCredentialId'.", 'startICloudSync [iCloudContactsList]');
            $this->delete();
            Log::d("Delete iCloudContactsList-model", 'startICloudSync [iCloudContactsList]');
            return;
        }

        $job = new Job();
        $job->type = Job::AddressImport;
        $job->user_id = $this->owner;
        $job->setJsonMeta(5, 0, $this->thirdPartyCredentialId, $this->findGreatestNumberOfListElements(), 0);

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

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

        return max($items);
    }

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