<?php

define('FLICKR_API_KEY', 'def990f52ff0874b671c54a92ff2636a');
define('FLICKR_API_SECRET', '8d877acb13b4e91d');

/**
 * Implements hook_boot().
 */
function mkbh_article_page_init()
{
    module_load_include('php', 'mkbh_article_page', 'lib/flickr');

    module_load_include('inc', 'mkbh_article_page', 'mkbh_article_page.helpers');
    module_load_include('inc', 'mkbh_article_page', 'mkbh_article_page.forms');

    // Add current path args to JS settings array for easy reference in CKEditor.
    drupal_add_js(['args' => arg()], 'setting');
}

/**
 * Implements hook_ctools_plugin_directory().
 *
 * @param $owner
 * @param $plugin_type
 *
 * @return string
 */
function mkbh_article_page_ctools_plugin_directory($owner, $plugin_type)
{
    if ($owner == 'ctools' && in_array($plugin_type, ['content_types'])) {
        return 'ctools/plugins/' . $plugin_type;
    }
}

/**
 * Implements hook_menu().
 */
function mkbh_article_page_menu()
{
    $items['ajax/mkbh-article-page/%node/inline-images'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_inline_images_callback',
        'page arguments' => [2],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    $items['ajax/mkbh-article-page/%node/inline-quotes'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_inline_quotes_callback',
        'page arguments' => [2],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    $items['ajax/mkbh-article-page/%node/inline-facts'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_inline_facts_callback',
        'page arguments' => [2],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    $items['ajax/mkbh-article-page/%node/inline-articles'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_inline_articles_callback',
        'page arguments' => [2],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    $items['ajax/mkbh-article-page/%node/inline-map-sources'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_inline_map_sources_callback',
        'page arguments' => [2],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    $items['ajax/mkbh-article-page/%node/parse-inline-map-token'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_parse_inline_map_token_callback',
        'page arguments' => [2],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    $items['ajax/mkbh-article-page/%node/parse-inline-map-token/%'] = [
        'type' => MENU_CALLBACK,
        'access arguments' => ['access content'],
        'page callback' => 'mkbh_article_ajax_parse_inline_map_token_callback',
        'page arguments' => [2, 4],
        'file' => 'mkbh_article_page.pages.inc',
    ];

    return $items;
}

/**
 * Implements hook_theme().
 */
function mkbh_article_page_theme($existing, $type, $theme, $path)
{
    return [
        'mkbh_article_content' => [
            'variables' => ['node' => NULL, 'sidebar' => NULL],
            'template' => 'templates/mkbh-article-content',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_photo_series_content' => [
            'variables' => ['node' => NULL, 'sidebar' => NULL],
            'template' => 'templates/mkbh-article-content',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_article_content_sidebar' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-article-content-sidebar',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_photo_series_photos' => [
            'variables' => [
                'node' => NULL,
                'photo_field_collection_items' => [],
            ],
            'template' => 'templates/mkbh-photo-series-photos',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_images' => [
            'variables' => ['node' => NULL, 'field_collection_items' => []],
            'template' => 'templates/mkbh-token-mkbh-inline-images',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_quote' => [
            'variables' => ['node' => NULL, 'quote' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-quote',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_fact' => [
            'variables' => ['node' => NULL, 'field_collection_items' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-fact',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_article' => [
            'variables' => ['node' => NULL, 'article' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-article',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_map' => [
            'variables' => [
                'node' => NULL,
                'title' => NULL,
                'preface' => NULL,
                'source' => NULL,
            ],
            'template' => 'templates/mkbh-token-mkbh-inline-map',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_ad' => [
            'variables' => [
                'node' => NULL,
                'ad_unit' => NULL,
            ],
            'template' => 'templates/mkbh-token-mkbh-inline-ad',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_city_change_analytics' => [
            'variables' => [
                'node' => NULL,
            ],
            'template' => 'templates/mkbh-token-mkbh-inline-city-change-analytics',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_city_change_suggestions' => [
            'variables' => [
                'node' => NULL,
            ],
            'template' => 'templates/mkbh-token-mkbh-inline-city-change-suggestions',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_du_skriver_modal' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-du-skriver-modal',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_visioner_modal' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-visioner-modal',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_mobile_pay' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-mobile-pay',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_photo_series_cta_email_modal' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-photo-series-cta-email-modal',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_token_mkbh_inline_top_reviews' => [
            'variables' => ['node' => NULL, 'reviewType' => NULL],
            'template' => 'templates/mkbh-token-mkbh-inline-top-reviews',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_project_information' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-project-information',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_project_bottom_section' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-project-bottom-section',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_project_bottom_section_block_instagram' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-project-bottom-section-block-instagram',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_project_bottom_section_block_related_articles' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-project-bottom-section-block-related-articles',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_project_bottom_section_block_project_photos' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-project-bottom-section-block-project-photos',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_sponsored_bottom_section' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-sponsored-bottom-section',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_sponsored_bottom_section_block_sponsored_highlight' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-sponsored-bottom-section-block-sponsored-highlight',
            'file' => 'mkbh_article_page.theme.inc',
        ],
        'mkbh_block_inline_vision_rate_widget' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-block-inline-vision-rate-widget',
            'file' => 'mkbh_article_page.theme.inc',
        ],

        'mkbh_form__mkbh_article_page_form_project_subscribe' => [
            'render element' => 'form',
            'template' => 'mkbh-form--mkbh-article-page-form-project-subscribe',
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/templates/forms',
        ],
        'mkbh_city_change_suggestions' => [
            'variables' => ['node' => NULL],
            'template' => 'templates/mkbh-city-change-suggestions',
            'file' => 'mkbh_article_page.theme.inc',
        ],
    ];
}

/**
 * Implements hook_ckeditor_plugin().
 */
function mkbh_article_page_ckeditor_plugin()
{
    return [
        'mkbh_inline_images' => [
            'name' => 'mkbh_inline_images',
            'desc' => t('MKBH: Easily insert inline images into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_images/',
            'buttons' => [
                'mkbh_inline_images' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Images')
                ]
            ]
        ],
        'mkbh_inline_quote' => [
            'name' => 'mkbh_inline_quote',
            'desc' => t('MKBH: Easily insert inline quote into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_quote/',
            'buttons' => [
                'mkbh_inline_quote' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Quote')
                ]
            ]
        ],
        'mkbh_inline_fact' => [
            'name' => 'mkbh_inline_fact',
            'desc' => t('MKBH: Easily insert inline fact into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_fact/',
            'buttons' => [
                'mkbh_inline_fact' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Fact')
                ]
            ]
        ],
        'mkbh_inline_article' => [
            'name' => 'mkbh_inline_article',
            'desc' => t('MKBH: Easily insert inline articles into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_article/',
            'buttons' => [
                'mkbh_inline_article' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Article')
                ]
            ]
        ],
        'mkbh_inline_map' => [
            'name' => 'mkbh_inline_map',
            'desc' => t('MKBH: Easily insert inline maps into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_map/',
            'buttons' => [
                'mkbh_inline_map' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Map')
                ]
            ]
        ],
        'mkbh_inline_ad' => [
            'name' => 'mkbh_inline_ad',
            'desc' => t('MKBH: Easily insert inline ads into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_ad/',
            'buttons' => [
                'mkbh_inline_ad' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Ad')
                ]
            ]
        ],
        'mkbh_inline_modal' => [
            'name' => 'mkbh_inline_modal',
            'desc' => t('MKBH: Easily insert inline modals into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_modal/',
            'buttons' => [
                'mkbh_inline_modal' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Modal')
                ]
            ]
        ],
        'mkbh_inline_top_reviews' => [
            'name' => 'mkbh_inline_top_reviews',
            'desc' => t('MKBH: Easily insert inline "Top Reviews" block into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_top_reviews/',
            'buttons' => [
                'mkbh_inline_top_reviews' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Top Reviews')
                ]
            ]
        ],
        'mkbh_inline_rate_widget' => [
            'name' => 'mkbh_inline_rate_widget',
            'desc' => t('MKBH: Easily insert inline Rate Widget block into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_inline_rate_widget/',
            'buttons' => [
                'mkbh_inline_rate_widget' => [
                    'icon' => 'images/button.svg',
                    'label' => t('Inline Rate Widget(Voting)')
                ]
            ]
        ],
        'mkbh_city_change_analytics' => [
            'name' => 'mkbh_city_change_analytics',
            'desc' => t('MKBH: Easily insert CityChange analytics into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_city_change_analytics/',
            'buttons' => [
                'mkbh_city_change_analytics' => [
                    'icon' => 'images/button.svg',
                    'label' => t('CityChange: Analytics'),
                ],
            ],
        ],
        'mkbh_city_change_suggestions' => [
            'name' => 'mkbh_city_change_suggestions',
            'desc' => t('MKBH: Easily insert CityChange suggestions into article content.'),
            'path' => drupal_get_path('module', 'mkbh_article_page') . '/ckeditor/plugins/mkbh_city_change_suggestions/',
            'buttons' => [
                'mkbh_city_change_suggestions' => [
                    'icon' => 'images/button.svg',
                    'label' => t('CityChange: Suggestions'),
                ],
            ],
        ],
    ];
}

/**
 * Implements hook_form_alter().
 */
function mkbh_article_page_form_node_form_alter(&$form, &$form_state)
{
    drupal_add_js(libraries_get_path('leaflet') . '/leaflet.js');
    drupal_add_js(libraries_get_path('leaflet') . '/Leaflet.fullscreen.js');

    drupal_add_css(libraries_get_path('leaflet') . '/leaflet.css');
    drupal_add_css(libraries_get_path('leaflet') . '/leaflet.fullscreen.css');

    drupal_add_js(libraries_get_path('isMobile') . '/isMobile.js');

    if (isset($form["field_node_writer_ref"])) {
        $form["field_node_writer_ref"]['#access'] = FALSE;
    }

    if (isset($form['#node']->location) && !empty($form['#node']->location)) {
        drupal_add_js([
            'mkbh_article_page_form_node_form_alter:' . $form['#node']->nid . ':location' => [
                'lat' => $form['#node']->location['latitude'],
                'lng' => $form['#node']->location['longitude'],
            ],
        ], 'setting');
    }

    if (isset($form['actions']['preview_changes'])) {
        hide($form['actions']['preview_changes']);
    }

    if (isset($form['field_article_inline_images'][LANGUAGE_NONE])) {
        foreach (element_children($form['field_article_inline_images'][LANGUAGE_NONE]) as $iiElementDelta) {
            $iiElement =& $form['field_article_inline_images'][LANGUAGE_NONE][$iiElementDelta];

            if (isset($iiElement['field_article_ii_layout'][LANGUAGE_NONE])) {
                unset($iiElement['field_article_ii_layout'][LANGUAGE_NONE]['#options']['_none']);
            }
        }
    }
}

/**
 * Implements hook_field_formatter_info().
 */
function mkbh_article_page_field_formatter_info()
{
    return [
        'image_fresco' => [
            'label' => t('Fresco Gallery'),
            'field types' => ['image'],
            'settings' => [
                'fresco_group' => 'article-inline-images-gallery',
                'fresco_caption' => 'auto',
                'image_style' => 'original',
            ],
        ],
    ];
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function mkbh_article_page_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state)
{
    $display = $instance['display'][$view_mode];
    $settings = $display['settings'];

    $element = [];

    $element['fresco_group'] = [
        '#type' => 'textfield',
        '#title' => t('Fresco Group'),
        '#description' => t('This is used to group images into galleries. All article detail page images are "article-inline-images-gallery" by default.'),
        '#default_value' => $settings['fresco_group'],
    ];

    $element['fresco_caption'] = [
        '#type' => 'textfield',
        '#title' => t('Fresco Caption'),
        '#description' => t('This is the caption to be displayed below image in Fresco. If "auto" caption will be pulled from image [Title] attribute.'),
        '#default_value' => $settings['fresco_caption'],
    ];

    $element['image_style'] = [
        '#type' => 'textfield',
        '#title' => t('Image Style'),
        '#description' => t('This is the image style which will be used to render image.'),
        '#default_value' => $settings['image_style'],
    ];

    return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function mkbh_article_page_field_formatter_settings_summary($field, $instance, $view_mode)
{
    $display = $instance['display'][$view_mode];
    $settings = $display['settings'];

    $summary = t('Fresco Group: @group. Fresco Caption: @caption. Image Style: @style', [
        '@group' => $settings['fresco_group'],
        '@caption' => $settings['fresco_caption'] == 'auto' ? t('Pulled from image [Title] attribute.') : $settings['fresco_caption'],
        '@style' => $settings['image_style'],
    ]);

    return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function mkbh_article_page_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display)
{
    $settings = $display['settings']; // get the settings

    $element = [];

    foreach ($items as $delta => $item) {
        $image = [
            '#theme' => 'image_style',
            '#style_name' => !empty($settings['image_style']) ? $settings['image_style'] : 'original',
            '#path' => $item['uri'],
            '#alt' => $item['alt'],
            '#title' => $item['title'],
        ];

        $element[] = [
            '#theme' => 'link',
            '#text' => render($image),
            '#path' => image_style_url('fresco_1200', $image['#path']),
            '#options' => [
                'attributes' => [
                    'class' => 'fresco',
                    'data-fresco-group' => $settings['fresco_group'],
                    'data-fresco-caption' => $settings['fresco_caption'] == 'auto' ? $image['#title'] : $settings['fresco_caption'],
                    'data-fresco-options' => 'loop: true',
                ],
                'html' => TRUE,
            ],
        ];
    }

    return $element;
}

/**
 * Implements hook_html_head_alter().
 */
function mkbh_article_page_html_head_alter(&$head_elements)
{
    $node = menu_get_object('node');
    $nodeWrapper = entity_metadata_wrapper('node', $node);

    $socialImage = NULL;

    // Reset canonical URL to include GET params, in order to allow Facebook fetch chosen image
    $currentPath = drupal_is_front_page() ? '/' : current_path();
    $head_elements['metatag_canonical']['#value'] = url($currentPath, ['absolute' => TRUE, 'query' => drupal_get_query_parameters()]);
    $head_elements['metatag_og:url_0']['#value'] = url($currentPath, ['absolute' => TRUE, 'query' => drupal_get_query_parameters()]);
    $head_elements['metatag_twitter:url_0']['#value'] = url($currentPath, ['absolute' => TRUE, 'query' => drupal_get_query_parameters()]);

    if ($nodeWrapper->value() && $nodeWrapper->getBundle() == 'photo_series') {
        if (empty($_GET['photo'])) {
            if (!empty($nodeWrapper->field_photo_main_image)) {
                $mainImage = $nodeWrapper->field_photo_main_image->field_photo_mi_image->value();
                if ($mainImage) {
                    $socialImage = $mainImage;
                }
            }
        } else {
            $fieldCollectionImage = entity_metadata_wrapper('field_collection_item', $_GET['photo']);

            if (!empty($fieldCollectionImage) && isset($fieldCollectionImage->field_photo_i_image)) {
                $sharedImage = $fieldCollectionImage->field_photo_i_image->value();
                if ($sharedImage) {
                    $socialImage = $sharedImage;
                }
            }
        }
    } elseif ($nodeWrapper->value()) {
        try {
            $mainImage = NULL;

            if (isset($nodeWrapper->field_article_main_image)) {
                $mainImage = $nodeWrapper->field_article_main_image->field_article_mi_image->value();
            } elseif (isset($nodeWrapper->field_project_main_image)) {
                $mainImage = $nodeWrapper->field_project_main_image->field_project_mi_image->value();
            } elseif (isset($nodeWrapper->field_review_main_image)) {
                $mainImage = $nodeWrapper->field_review_main_image->field_review_mi_image->value();
            } elseif (isset($nodeWrapper->field_write_main_image)) {
                $mainImage = $nodeWrapper->field_write_main_image->field_write_mi_image->value();
            }

            if (!is_null($mainImage)) {
                $socialImage = $mainImage;
            }
        } catch (Exception $e) {
            watchdog('mkbh_article_page_html_head_alter', $e->getMessage(), [], WATCHDOG_INFO);
        }
    }

    if (!is_null($socialImage)) {
        // Remove all already set images...
        $hasImage = false;
        foreach ($head_elements as $key => $value) {
            if (strpos($key, 'metatag_og:image') !== FALSE) {
//                unset($head_elements[$key]);
                $hasImage = true;
            }
        }

        if (!$hasImage) {
            $head_elements['metatag_og:image_0'] = [
                '#theme' => 'metatag_property',
                '#tag' => 'meta',
                '#id' => 'metatag_og:image_0',
                '#name' => 'og:image',
                '#value' => image_style_url('1200x630', $socialImage['uri']),
                '#type' => 'html_tag',
            ];

            $head_elements['metatag_og:image:width_0'] = [
                '#theme' => 'metatag_property',
                '#tag' => 'meta',
                '#id' => 'metatag_og:image:width_0',
                '#name' => 'og:image:width',
                '#value' => '1200',
                '#type' => 'html_tag',
            ];

            $head_elements['metatag_og:image:height_0'] = [
                '#theme' => 'metatag_property',
                '#tag' => 'meta',
                '#id' => 'metatag_og:image:height_0',
                '#name' => 'og:image:height',
                '#value' => '630',
                '#type' => 'html_tag',
            ];
        }
    }

    if (isset($head_elements['meta-fcb'])) {
        unset($head_elements['meta-fcb']);
    }
}

/**
 * Implements hook_entity_info().
 */
function mkbh_article_page_entity_info()
{
    $info['mkbh_project_subscriber'] = [
        'label' => t('MKBH Project Subscriber'),
        'base table' => 'mkbh_project_subscribers',
        'entity keys' => [
            'id' => 'id',
        ],
        'module' => 'mkbh_article_page',
        'entity class' => 'Entity',
        'controller class' => 'MKBHProjectSubscriberEntityController',
        'views controller class' => 'EntityDefaultViewsController',
    ];

    return $info;
}

/**
 * Implements hook_entity_property_info().
 */
function mkbh_article_page_entity_property_info()
{
    $info['mkbh_project_subscriber']['properties']['user_id'] = [
        'label' => t('Subscriber User ID'),
        'type' => 'user',
        'schema field' => 'user_id',
    ];

    $info['mkbh_project_subscriber']['properties']['project_id'] = [
        'label' => t('Project Node ID'),
        'type' => 'node',
        'schema field' => 'project_id',
    ];

    $info['mkbh_project_subscriber']['properties']['created_at'] = [
        'label' => t('Subscriber Created Date'),
        'type' => 'date',
        'schema field' => 'created_at',
    ];

    $info['mkbh_project_subscriber']['properties']['updated_at'] = [
        'label' => t('Subscriber Last Updated Date'),
        'type' => 'date',
        'schema field' => 'updated_at',
    ];

    return $info;
}

/**
 * Implements hook_entity_insert().
 */
function mkbh_article_page_entity_insert($entity, $type)
{
    $entityWrapper = entity_metadata_wrapper($type, $entity);
    if (isset($entityWrapper->field_related_projects)) {
        $relatedProjectIds = array_map(function ($e) {
            return $e->nid;
        }, $entityWrapper->field_related_projects->value());

        if ($relatedProjectIds) {
            foreach ($relatedProjectIds as $addedProjectId) {
                $projectWrapper = entity_metadata_wrapper('node', $addedProjectId);
                rules_invoke_event('mkbh_related_project_added', $projectWrapper->value(), $entity);
            }
        }
    }
}

/**
 * Implements hook_entity_update().
 *
 * @param $entity
 * @param $type
 */
function mkbh_article_page_entity_update($entity, $type)
{
    $entityWrapper = entity_metadata_wrapper($type, $entity);
    if (isset($entityWrapper->field_related_projects)) {
        module_load_include('inc', 'mkbh_article_page', 'mkbh_article_page.helpers');
        $relatedProjectsDifference = _mkbh_article_page_get_entity_added_projects($entity, $type);

        if ($relatedProjectsDifference) {
            foreach ($relatedProjectsDifference as $addedProjectId) {
                $projectWrapper = entity_metadata_wrapper('node', $addedProjectId);
                rules_invoke_event('mkbh_related_project_added', $projectWrapper->value(), $entity);
            }
        }
    }
}

/**
 * Implements hook_mail().
 *
 * Set's the message subject and body as configured.
 */
function mkbh_article_page_mail($key, &$message, $params)
{
    $message['subject'] .= str_replace(["\r", "\n"], '', $params['subject']);
    $message['body'][] = $params['message'];
}

/**
 * Implements hook_token_info().
 */
function mkbh_article_page_token_info()
{
    return [
        'tokens' => [
            'node' => [
                'node_custom_url_prefix' => [
                    'name' => t("Node custom URL Prefix"),
                    'description' => t("Node custom URL Prefix"),
                ],
            ],
        ],
    ];
}

/**
 * Implements hook_tokens().
 */
function mkbh_article_page_tokens($type, $tokens, array $data = [], array $options = [])
{
    $replacements = [];

    if ($type == 'node') {
        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'node_custom_url_prefix':
                    $replacements[$original] = 'indhold';

                    switch ($data['node']->type) {
                        case 'vision':
                            $replacements[$original] = 'vision';
                            break;

                        case 'projekt':
                            $replacements[$original] = 'projekt';
                            break;

                        case 'photo_series':
                            $replacements[$original] = 'foto';
                            break;

                        default:
                        case 'article':
                            $replacements[$original] = 'indhold';

                            try {
                                $adapterName = ucwords(str_replace(['-', '_', ' '], ' ', $data['node']->type));
                                $className = 'Drupal\mkbh_blocks\Adapter\Node' . str_replace(' ', '', $adapterName) . 'Adapter';

                                if (class_exists($className)) {
                                    /** @var \Drupal\mkbh_blocks\Adapter\NodeAdapterInterface $adapter */
                                    $adapter = new Drupal\mkbh_blocks\Adapter\NodeAdapterProxy($data['node']);

                                    if ($adapter->getArticleType() == 8) { // opinion
                                        $replacements[$original] = 'opinion';
                                    }
                                }
                            } catch (Exception $e) {
                                watchdog('mkbh_article_page_tokens', $e->getMessage(), [], WATCHDOG_ERROR);
                                $replacements[$original] = 'indhold';
                            }

                            break;
                    }

                    break;
            }
        }
    }

    return $replacements;
}

/**
 * Implements hook_tokens_alter().
 */
function mkbh_article_page_tokens_alter(array &$replacements, array $context)
{
    if (isset($replacements['[node:summary]'])) {
        $replacements['[node:summary]'] = _mkbh_article_page_tokens_clear($replacements['[node:summary]'], ['node' => $context['data']['node']]);
        $replacements['[node:summary]'] = str_ireplace([
            '<p></p>',
            "<p>\n</p>",
            '<p>&nbsp;</p>',
            "\n",
        ], '', $replacements['[node:summary]']);
    }
}

/**
 * Implements hook_views_pre_execute().
 */
function mkbh_article_page_views_pre_view(&$view)
{
    if ($view->name == 'article_mest_laeste' && $view->current_display == 'pane_article_mest_leste') {
        $currentNode = menu_get_object();

        if ($currentNode->type == 'review') {
            $nodeWrapper = entity_metadata_wrapper('node', $currentNode);
            $reviewTypeTid = $nodeWrapper->field_review_type->raw();

            if (is_numeric($reviewTypeTid)) {
                $filters = $view->display_handler->get_option('filters');

                $filters['type']['value'] = ['review' => 'review'];
                $filters['field_review_type_target_id'] = [
                    'id' => 'field_review_type_target_id',
                    'table' => 'field_data_field_review_type',
                    'field' => 'field_review_type_target_id',
                    'relationship' => 'none',
                    'group_type' => 'group',
                    'ui_name' => '',
                    'operator' => 'in',
                    'value' => [$reviewTypeTid => $reviewTypeTid],
                    'group' => '1',
                    'exposed' => FALSE,
                ];

                $view->display_handler->override_option('filters', $filters);
            }
        }
    }
}

/**
 * Implements hook_node_access().
 */
function mkbh_article_page_node_access($node, $op, $account)
{
    if ($op == 'view' && !$node->status && (isset($account->roles) && in_array('can view unpublished', $account->roles))) {
        return NODE_ACCESS_ALLOW;
    }

    return NODE_ACCESS_IGNORE;
}

/**
 * Implements hook_field_display_alter().
 */
function mkbh_article_page_field_display_alter(&$display, $context)
{
    $frescoFields = [
        'field_article_ii_image' => 'field_article_ii_caption',
        'field_article_mi_image' => 'field_article_mi_caption',
        'field_photo_i_image' => 'field_photo_i_caption',
        'field_photo_mi_image' => 'field_photo_mi_caption',
        'field_project_mi_image' => 'field_project_mi_caption',
        'field_review_ii_image' => 'field_review_ii_caption',
        'field_review_mi_image' => 'field_review_mi_caption',
        'field_write_mi_image' => 'field_write_mi_caption',
    ];

    if ($display['type'] === 'image_fresco' && array_key_exists($context['field']['field_name'], $frescoFields)) {
        $wrapper = entity_metadata_wrapper('field_collection_item', $context['entity']);
        $caption = $wrapper->{$frescoFields[$context['field']['field_name']]}->value();

        if ($caption) {
            $display['settings']['fresco_caption'] = $caption;
        }
    }
}

/**
 * Implementation of hook_field_access().
 */
function mkbh_article_page_field_access($op, $field, $entity_type, $entity, $account)
{
    if ($op == 'view' && $field['field_name'] === 'field_article_mp3' && $entity->field_article_mp3) {
        if (!mkbh_paywall_is_user_has_access($entity)) {
            return FALSE;
        }
    }
}

/**
 * Implementation of hook_node_presave().
 */
function mkbh_article_page_node_presave($node)
{
    if (!property_exists($node, 'field_article_name_of_writer') ||
        !property_exists($node, 'field_node_writer_ref')) {
        return NULL;
    }

    $optimized_map = &drupal_static(__FUNCTION__);
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $node_writer_name = $node_wrapper->field_article_name_of_writer->value();


    $node_writer_name_trim = trim($node_writer_name);
    if (!$node_writer_name_trim) {
        return NULL;
    }

    if (!isset($optimized_map[$node_writer_name_trim])) {
        $query = new EntityFieldQuery();
        $terms = $query->entityCondition('entity_type', 'taxonomy_term')
            ->propertyCondition('name', $node_writer_name_trim)
            ->execute();
        if (empty($terms['taxonomy_term'])) {
            // Only this method allow clear data , set(NULL) or assign NULL || [] not working
            $node_wrapper->field_node_writer_ref->set(0);
            return NULL;
        }
        $first_term = reset($terms['taxonomy_term']);
        $optimized_map[$node_writer_name_trim] = $first_term->tid;
    }

    if (!isset($optimized_map[$node_writer_name_trim])) {
        $node_wrapper->field_node_writer_ref->set(0);
    } else {
        $node_wrapper->field_node_writer_ref->set($optimized_map[$node_writer_name_trim]);
    }
}

/**
 * Implementation of hook_taxonomy_term_insert().
 */
function mkbh_article_page_taxonomy_term_insert($term)
{
    mkbh_article_page_taxonomy_term_update($term);
}

/**
 * Implementation of hook_taxonomy_term_update().
 */
function mkbh_article_page_taxonomy_term_update($term)
{

    $query = new EntityFieldQuery();
    $node_existed_ids = $query->entityCondition('entity_type', 'node')
        ->fieldCondition('field_node_writer_ref', 'target_id', $term->tid)
        // ->fieldCondition('field_article_name_of_writer', 'value', trim($term->name))
        ->execute();

    $query2 = new EntityFieldQuery();
    $node_need_ids = $query2->entityCondition('entity_type', 'node')
        // ->fieldCondition('field_node_writer_ref', 'target_id', $term->tid)
        ->fieldCondition('field_article_name_of_writer', 'value', trim($term->name))
        ->execute();

    if (!empty($node_existed_ids['node'])) {
        $existed_ids = array_keys($node_existed_ids['node']);
        if (!empty($node_need_ids['node'])) {
            $need_ids = array_keys($node_need_ids['node']);
            $changed_ids = array_merge(array_diff($existed_ids, $need_ids), array_diff($need_ids, $existed_ids));

        } else {

            $changed_ids = $existed_ids;
        }
    } else {
        if (!empty($node_need_ids['node'])) {
            $changed_ids = array_keys($node_need_ids['node']);
        } else {
            return NULL;
        }
    }

    $nodes = node_load_multiple($changed_ids);
    if (empty($nodes)) {
        return NULL;
    }
    foreach ($nodes as $node) {
        $changed = $node->changed;
        node_save($node);
        // Node force change changed property so we must fix it.
        $node->changed = $changed;
        drupal_write_record('node', $node, 'nid');
    }
}


/**
 * Implementation of hook_form_ID_FORM_alter().
 */
function mkbh_article_page_form_taxonomy_form_term_alter(&$form, &$form_state)
{
    # Hide unnecessary elements tvi module.
    $form['#attached']['css'][] = ['data' => 'form[id^=taxonomy-form-term] [id^=edit-tvi]{ display:none }', 'type' => 'inline'];
}
