<?php

abstract class AbstractLdapImporter
{

    abstract protected function getModelInstance($ldapId, $ldapInterfaceId);

    abstract protected function loadLdapRelatedModels($ldapInterfaceId);

    abstract protected function updateContact($attributes, $ldapInterface);

    public function import($ldaptContacts, $ldapInterface)
    {
        $totalItemCount = count($ldaptContacts);
        Log::v("Importing $totalItemCount contacts from LDAP server.", 'LdapImporter');
        if ($totalItemCount > 0) {
            $this->importLdapContacts($ldaptContacts, $ldapInterface);
        }
    }

    protected function importLdapContacts($ldaptContacts, $ldapInterface)
    {
        $selectedItems = json_decode($ldapInterface->selectedItems, true);
        $regEx = json_decode($ldapInterface->regEx, true);

        foreach ($ldaptContacts as $contact) {
            $attributes = $this->getContactsData($selectedItems, $contact, $regEx);
            if (!empty($attributes)) {
                Log::d("Updating $ldapInterface->connectedModel " . $attributes['ldapId'], 'LdapImport');
                $this->updateContact($attributes, $ldapInterface);
            } else {
                Log::e("Could not get ldapId", "LdapImport");
            }
        }
    }

    protected function getContactsData($selectedItems, $contact, $regEx)
    {
        $contactsData = array();
        foreach ($selectedItems as $key => $value) {
            if (array_key_exists($value, $contact)) {
                $attribute = $contact[$value];
                if (!empty($regEx) && isset($regEx[$value]) && is_array($regEx[$value])) {
                    $match = "/" . $regEx[$value][0] . "/";
                    $replace = $regEx[$value][1];
                    if (@preg_match($match, $attribute) === 1) {
                        $attribute = preg_replace($match, $replace, $attribute);
                    }
                }
                $contactsData[$key] = ($key == 'name') ? strtolower($attribute) : $attribute;
            } else {
                $contactsData[$key] = '';
            }
        }
        return $contactsData;
    }
}
