<?php

namespace Eventman\Admin;


use plainview\sdk_broadcast\collections\collection;
use threewp_broadcast\api\api;
use threewp_broadcast\ThreeWP_Broadcast;

class WPML
{

    use LogTrait;

    private $codes = ['WPML_API_SUCCESS' => 0,
        'WPML_API_ERROR' => 99,
        'WPML_API_INVALID_LANGUAGE_CODE' => 1,
        'WPML_API_INVALID_TRID' => 2,
        'WPML_API_LANGUAGE_CODE_EXISTS' => 3,
        'WPML_API_CONTENT_NOT_FOUND' => 4,
        'WPML_API_TRANSLATION_NOT_FOUND' => 5,
        'WPML_API_INVALID_CONTENT_TYPE' => 6,
        'WPML_API_CONTENT_EXISTS' => 7,
        'WPML_API_FUNCTION_ALREADY_DECLARED' => 8,
        'WPML_API_CONTENT_TRANSLATION_DISABLED' => 9];

    /**
     * Broadcast completed WPML translations to the blogs the original post is broadcasted to.
     *
     * Meant to be executed on 'wpml_pro_translation_completed', but works with any post id of a translation post.
     *
     * @param $postId string|int post ID of translation post.
     */
    public function broadcastCompletedTranslation($postId)
    {
        $this->log('Starting broadcast on translation finish.');
        // Get original post
        $originalPostId = apply_filters('wpml_original_element_id', NULL, $postId);
        if ($originalPostId) {
            $this->log("Translation post id: $postId, Original post id: $originalPostId");
            // get the broadcast links for original post
            $api = new api();
            $originalPostLinkController = $api->linking($originalPostId);

//            $this->log("Got original post linking: " . join(" -> ", $originalPostLinkController->));
            if ($originalPostLinkController->is_parent()) {
                // post is parent post
                $broadcastedBlogIds = array_keys($originalPostLinkController->children());

                // get the translation links
                $translationLinkController = $api->linking($postId);
                $translationBroadcastedBlogIds = array_keys($translationLinkController->children());

                // diff blog ids for translation and original
//                $blogIdsToBroadcastTo = array_diff($broadcastedBlogIds, $translationBroadcastedBlogIds);
                $this->log("Broadcasting translation to: " . join(', ', $broadcastedBlogIds));

                // broadcast to remaining blogs
                $api->broadcast_children($postId, $broadcastedBlogIds);
            }
        }
    }

    /**
     * From 3rd_party_pack
     * @param $action
     */
    public function fixedCollectPostTypeTaxonomies($action)
    {
        $bcd = $action->broadcasting_data;

        if (!$this->has_wpml())
            return;

        global $wpdb;


        if (isset($bcd->wpml))
            return;
        $bcd->wpml = ThreeWP_Broadcast()->collection();
        // For convenience
        $td = $bcd->wpml->collection('taxonomy_data');

        foreach ($bcd->parent_blog_taxonomies as $taxonomy => $data) {
            foreach ($data['terms'] as $term)
                $this->saveTermTranslations($td, $term);
        }

        // Why are we saving this here? Because (1) the wp_insert_term action does not supply a bcd, and (2) we might not be broadcasting at all.
        $this->__wpml_data = $bcd->wpml;
    }

    /**
     * From 3rd_party_pack.
     * Fixed wpml_get_content_translations returning an error code, checking whether it returns an array.
     * @brief        Recursively save the term translations into this collection.
     * @param collection $collection
     * @param $term
     * @since        2017-08-09 16:05:57
     */
    public function saveTermTranslations(collection $collection, \WP_Term $term = null)
    {
        if (is_null($term)) {
            return;
        }
        $content_id = $term->term_id;
        $content_type = 'tax_' . $term->taxonomy;
        $taxonomy = $term->taxonomy;
        $translations = wpml_get_content_translations($content_type, $content_id);
        if (is_array($translations)) {
            foreach ($translations as $term_language => $translated_term_id) {
                $translated_term = get_term($translated_term_id, $taxonomy);
                // Put the term in an index per slug and per language.
                $translations = $collection->collection('translations');
                $translations->collection($term->slug)
                    ->set($term_language, $translated_term);

                if (!$translations->has($translated_term->slug)) {
                    $this->saveTermTranslations($collection, $translated_term);
                }
            }
        } elseif (is_int($translations)) {
            $c = array_flip($this->codes);

            $error = $c[$translations] ?? $translations;

            $this->log("Could not save term translations for $content_type $content_id. WPML API Error code: $error");
        } else {
            $e = function_exists('dump') ? dump($translations) : 'e';
            $this->log("Could not save term translations for $content_type $content_id. Unknown Error. " . $e);
        }
    }

    /**
     * From 3rd_party_pack
     * @brief        Check for the existence of WPML.
     * @return        bool        True if WPML is alive and kicking. Else false.
     * @since        20140101
     **/
    public function has_wpml()
    {
        $defined = defined('ICL_SITEPRESS_VERSION');
        if ($defined)
            require_once(ICL_PLUGIN_PATH . '/inc/wpml-api.php');
        return $defined;
    }

}