<?php

require_once __DIR__ . "/../../../../extensions/HybridAuth/hybridauth-2.6.0/additional-providers/hybridauth-xing/Providers/XING.php";

class plXING extends Hybrid_Providers_XING
{

    private $address;

    function getTotalContactCount()
    {
        $userFields = $this->getUserFields();
        $url = "users/me/contacts";
        $url .= "?limit=1";
        $url .= "&user_fields=" . implode(",", $userFields);
        $url .= "&offset=0";

        $response = $this->api->get($url);
        if (isset($response->contacts)) {
            return $response->contacts->total;
        } else {
            throw new CHttpException(404, 'Invalid OAuth token: Session not found or revoked');
        }
    }

    function getUserContacts($arguments = array())
    {
        $userFields = $this->getUserFields();
        $url = "users/me/contacts";
        $url .= "?limit=" . $arguments["limit"];
        $url .= "&user_fields=" . implode(",", $userFields);
        $url .= "&offset=" . $arguments["offset"];

        $response = $this->api->get($url);
        foreach ($response->contacts->users as $contactData) {
            $this->importAddresses($arguments['model'], $contactData);
            $this->saveAddressModel();
        }
    }

    private function getUserFields()
    {
        return array(
            "id",
            "first_name",
            "last_name",
            "display_name",
            "permalink",
            "web_profiles",
            "photo_urls",
            "display_name",
            "interests",
            "active_email",
            "private_address",
            "business_address",
            "birth_date",
            "professional_experience"
        );
    }

    function importAddresses($model, $contactData)
    {
        $this->getAddressesModel($contactData, $model);

        $this->setModelData($model);
        $this->setPersonalData($contactData);
        $this->addAddressData($contactData);

        if (property_exists($contactData, 'photo_urls') && property_exists($contactData->photo_urls, 'large')) {
            $this->address->contact_jpegphoto = $contactData->photo_urls->large;
        }

        if (property_exists($contactData, 'birth_date')) {
            $this->formateBirthDate($contactData->birth_date);
        } else {
            $this->address->contact_bday = null;
        }

        if (property_exists($contactData, 'professional_experience')) {
            $this->setCompanyData($contactData->professional_experience);
        }

        if (property_exists($contactData, 'web_profiles') && !empty((array) $contactData->web_profiles)) {
            $this->setWebProfiles($contactData);
        }
    }

    private function setCompanyData($companyData)
    {
        if (property_exists($companyData, 'primary_company')) {
            $this->address->org_name = property_exists($companyData->primary_company, 'name') ? $companyData->primary_company->name : null;
            $this->setCompanyRole($companyData->primary_company);
            $this->address->contact_url = property_exists($companyData->primary_company, 'url') ? $companyData->primary_company->url : null;
        }
    }

    private function setCompanyRole($companyData)
    {

        if (property_exists($companyData, 'title')) {
            if (strlen($companyData->title) <= 64) {
                $this->address->contact_role = $companyData->title;
            } else {
                $this->address->contact_label = $companyData->title;
            }
        }
    }

    private function formateBirthDate($birthDay)
    {
        if ($birthDay->year && $birthDay->month && $birthDay->day) {
            if (strlen($birthDay->month) == 1) {
                $birthDay->month = '0' . $birthDay->month;
            }
            if (strlen($birthDay->day) == 1) {
                $birthDay->day = '0' . $birthDay->day;
            }
            $this->address->contact_bday = PhonalisaDate::newServerDate($birthDay->year . '-' . $birthDay->month . '-' . $birthDay->day, "Y-m-d");
        } else {
            $this->address->contact_bday = "";
        }
    }

    private function getAddressesModel($contactData, $model)
    {
        $address = Addresses::model()->findByAttributes(
                array('xingId' => $contactData->id,
                    'contact_tid' => $model->addressBookId
                )
        );
        if ($address) {
            $this->address = $address;
        } else {
            $this->address = new Addresses();
            $this->address->xingId = (property_exists($contactData, 'id')) ? $contactData->id : '';
        }
    }

    private function setModelData($model)
    {
        $this->address->contact_tid = $model->addressBookId;
        $this->address->contact_owner = $model->owner;
        $this->address->source = AddressSourceType::getSourceTypeFromProvider($model->provider);
    }

    private function setPersonalData($contactData)
    {
        $this->address->n_family = (property_exists($contactData, 'last_name')) ? $contactData->last_name : '';
        $this->address->n_given = (property_exists($contactData, 'first_name')) ? $contactData->first_name : '';
        $this->address->n_fn = (property_exists($contactData, 'display_name')) ? $contactData->display_name : '';
        $this->address->contact_label = (property_exists($contactData, 'description')) ? $contactData->description : '';
        $this->address->contact_note = (property_exists($contactData, 'interests')) ? $contactData->interests : '';
    }

    private function addAddressData($contactData)
    {
        if (property_exists($contactData, 'private_address')) {
            $this->setPrivateData($contactData->private_address);
        }
        if (property_exists($contactData, 'business_address')) {
            $this->setWorkData($contactData->business_address);
        }
    }

    private function setPrivateData($privateData)
    {
        $contactData = $this->getContactData($privateData);
        foreach ($contactData as $key => $value) {
            if ($key === 'tel_cell') {
                $key .= '_private';
                $this->address->$key = $value;
            } else {
                $key .= '_home';
                $this->address->$key = $value;
            }
        }
        $this->setAddressData($privateData, 'adr_two_');
    }

    private function setWorkData($workData)
    {
        $contactData = $this->getContactData($workData);
        foreach ($contactData as $key => $value) {
            if ($key === 'tel') {
                $attribute = $key . '_work';
                $this->address->$attribute = $value;
            } else {
                $this->address->$key = $value;
            }
        }
        $this->setAddressData($workData, 'adr_one_');
    }

    private function setAddressData($workAddress, $type)
    {
        $addressData = $this->getAddressData($workAddress);
        foreach ($addressData as $key => $value) {
            $attribute = $type . $key;
            $this->address->$attribute = $value;
        }
    }

    private function getContactData($contactData)
    {
        return array(
            'tel_cell' => $this->getFormatedPhoneNumbers($contactData->mobile_phone),
            'tel_fax' => $this->getFormatedPhoneNumbers($contactData->fax),
            'tel' => $this->getFormatedPhoneNumbers($contactData->phone),
            'contact_email' => $contactData->email,
        );
    }

    private function getAddressData($addressData)
    {
        return array(
            'street' => $addressData->street,
            'postalcode' => $addressData->zip_code,
            'locality' => $addressData->city,
            'countryname' => $addressData->country
        );
    }

    private function setWebProfiles($contactData)
    {
        $socialData = $this->getSocialAcoountData($contactData->web_profiles);
        foreach ($socialData as $key => $value) {
            $this->address->$key = $value;
        }
        $this->address->xing_profile_url = (property_exists($contactData, 'permalink')) ? $contactData->permalink : '';

        if (property_exists($contactData->web_profiles, 'homepage') && is_array($contactData->web_profiles->homepage)) {
            $this->address->contact_url_home = array_shift($contactData->web_profiles->homepage);
        }
    }

    private function getSocialAcoountData($webProfiles)
    {
        $socialAcoountData = array();
        if (property_exists($webProfiles, 'facebook') && is_array($webProfiles->facebook)) {
            $socialAcoountData['facebook_profile_url'] = array_shift($webProfiles->facebook);
        }
        if (property_exists($webProfiles, 'twitter') && is_array($webProfiles->twitter)) {
            $socialAcoountData['twitter_profile_url'] = array_shift($webProfiles->twitter);
        }

        return $socialAcoountData;
    }

    private function getFormatedPhoneNumbers($number)
    {
        if (strlen($number) <= 40) {
            if (isset($number)) {
                $number = preg_replace('/^49/', '+49', $number);
                $number = str_replace('|', '-', $number);
            }
            return $number;
        } else {
            return null;
        }
    }

    private function saveAddressModel()
    {
        if (!$this->address->save()) {
            Log::e('An error has occurred saving addresses model', 'ThirdPartyCredentials [plXING]');
            Log::e('User-ID: ' . $this->address->contact_owner, 'ThirdPartyCredentials [plXING]');
            Log::e('Error Text : ' . json_encode($this->address->errors), 'ThirdPartyCredentials [plXING]');
        }
    }
}
