<?php

/**
 * Implements hook_init().
 */
function mkbh_video_player_init()
{
    module_load_include('inc', 'filefield_sources', 'sources/attach');
}

/**
 * Implements hook_theme().
 */
function mkbh_video_player_theme($existing, $type, $theme, $path)
{
    return [
        'video_player_flowplayer' => [
            'variables' => ['video' => NULL],
            'template' => 'templates/video-player-flowplayer',
            'file' => 'mkbh_video_player.theme.inc',
        ],
    ];
}

/**
 * Implements hook_field_formatter_info().
 * {@inheritdoc}
 */
function mkbh_video_player_field_formatter_info()
{
    return [
        'video_flowplayer' => [
            'label' => t('Flow Player'),
            'field types' => ['video'],
        ],
    ];
}

/**
 * Implements hook_field_formatter_view().
 * {@inheritdoc}
 */
function mkbh_video_player_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display)
{
    $element = [];

    switch ($display['type']) {
        case 'video_flowplayer':
            $modulePath = drupal_get_path('module', 'mkbh_video_player');

            drupal_add_css($modulePath . '/assets/less/flowplayer.less');
            drupal_add_css($modulePath . '/assets/plugins/flowplayer/skin/skin.css');
            drupal_add_js($modulePath . '/assets/plugins/flowplayer/flowplayer.min.js');
            drupal_add_js($modulePath . '/assets/javascripts/flowplayer.js');

            foreach ($items as $delta => $item) {
                $element[$delta] = [
                    '#theme' => 'video_player_flowplayer',
                    '#video' => $item,
                ];
            }

            break;
    }

    return $element;
}

/**
 * Implements hook_field_widget_form_alter().
 */
function mkbh_video_player_field_widget_form_alter(&$element, &$form_state, $context)
{
    if ($context['field']['type'] == 'video') {
        foreach (element_children($element) as $key => $child) {
            $element[$key]['#process'][] = 'mkbh_video_player_video_field_widget_process';
        }
    }
}

/**
 * Process function for video fields.
 *
 * @param $element
 * @param $form_state
 * @param $form
 *
 * @return mixed
 */
function mkbh_video_player_video_field_widget_process($element, &$form_state, $form)
{
    $element['thumbnail']['#states'] = [
        'invisible' => [
            ':input[name="' . ($element['#name'] . '[use_default_video_thumb]') . '"]' => ['checked' => TRUE],
        ],
    ];

    return $element;
}
