<?php

class LdapImportCronJob extends AbstractCronJob
{

    public function run()
    {
        $jobs = Job::model()->findAllByAttributes(array('type' => Job::LDAPImport));
        foreach ($jobs as $importJob) {
            if ($importJob->status == Job::Finished) {
                $importJob->delete();
            } else if ($importJob->status == Job::Failed) {
                continue;
            } else {
                $importJob->status = Job::Running;
                $this->startLdapImport($importJob);
            }
        }
    }

    public function getCronRule()
    {
        return '* * * * *';
    }

    private function startLdapImport($job)
    {
        $meta = $job->getJsonMeta();
        if (isset($meta)) {
            $this->import($job, $meta);
            if ($job->progress == LdapConnecter::IMPORT_FINISHED) {
                $job->status = Job::Finished;
            } else {
                $job->status = Job::Running;
            }
        }
        if (!$job->save()) {
            $this->createJobErrorLogMessage($job);
        }
    }

    private function import($job, $meta)
    {
        $ldapConnector = new LdapConnecter();
        if (property_exists($meta, "LdapInterfaceId")) {
            $ldapInterface = LdapInterface::model()->findByPk($meta->LdapInterfaceId);
            if (isset($ldapInterface)) {
                Log::v("Starting LDAP-Import for interface ID: $ldapInterface->id", "LdapImportCronJob");
                $importProgress = (int) $job->progress;
                $importer = LdapImporterFactory::generateImporterOfType($ldapInterface->connectedModel);
                $ldaptContacts = $ldapConnector->getLdapContacts($ldapInterface, $importProgress);
                $importer->import($ldaptContacts, $ldapInterface);
                $job->progress = $importProgress;
            } else {
                $job->status = Job::Failed;
                $job->addError('LdapInterface', "The requested model with Id $meta->LdapInterfaceId does not exist.");
            }
        } else {
            $job->status = Job::Failed;
            $job->addError('Job meta', "Missing LdapInterfaceId in meta data.");
        }
    }

    private function createJobErrorLogMessage($job)
    {
        Log::e("An error has occurred in Job:  ID $job->id", 'LdapImportCronJob');
        Log::e("User-ID: $job->user_id", 'LdapImportCronJob');
        Log::e('Status: ' . $job->status, 'LdapImportCronJob');
        Log::e('Error Text : ' . json_encode($job->errors), 'LdapImportCronJob');
    }
}
