<?php

class LdapAddressImporter extends AbstractLdapImporter
{

    protected function loadLdapRelatedModels($ldapInterfaceId)
    {
        return Addresses::model()->findAllByAttributes(array('ldapInterface' => $ldapInterfaceId));
    }

    protected function updateContact($attributes, $ldapInterface)
    {
        $address = $this->getModelInstance($attributes['ldapId'], $ldapInterface->id);
        $this->checkAttributesLength($attributes);
        $address->attributes = $attributes;
        $address->contact_owner = $ldapInterface->owner;
        $address->contact_tid = $ldapInterface->addressBookID;
        if (!$address->save()) {
            Log::e("Address $address->ldapId can not be saved.", "LDAP Interface");
            Log::e(json_encode($address->errors), "LDAP Interface");
        }
    }

    protected function getModelInstance($ldapId, $ldapInterfaceId)
    {
        $model = Addresses::model()->findByAttributes(
                [
                    'ldapId' => $ldapId,
                    'ldapInterface' => $ldapInterfaceId
                ]
        );
        if (!isset($model)) {
            Log::d("Creating new address for LDAP ID $ldapId.", 'LdapUserImporter');
            $model = new Addresses();
            $model->source = AddressSourceType::LDAP;
            $model->ldapInterface = $ldapInterfaceId;
        }
        $model->scenario = 'LdapImport';

        return $model;
    }

    private function checkAttributesLength(&$attributes)
    {
        $attributesList = $this->getAttributesList();
        foreach ($attributes as $key => $attribute) {
            foreach ($attributesList as $maxLength => $keyList) {
                if (in_array($key, $keyList)) {
                    $this->trimAttributeLength($attribute, $maxLength);
                    $attributes[$key] = $attribute;
                }
            }
        }
    }

    private function getAttributesList()
    {
        return array(
            40 => array('tel_home', 'tel_cell', 'tel_cell_private', 'tel_work', 'tel_fax', 'tel_fax_home'),
            64 => array('n_family', 'n_given', 'n_middle', 'n_prefix', 'n_suffix', 'org_unit', 'contact_role',
                'adr_one_street', 'adr_one_locality', 'adr_one_region', 'adr_one_postalcode', 'adr_one_countryname'),
            128 => array('org_name', 'contact_email', 'contact_email_home', 'contact_url', 'contact_url_home'),
            255 => array('twitter_profile_url', 'linkedin_profile_url', 'facebook_profile_url'));
    }

    private function trimAttributeLength(&$attribute, $maxLength)
    {
        if (strlen($attribute) > $maxLength) {
            $attribute = substr($attribute, 0, $maxLength - 1);
        }
    }
}
