<?php

require_once(dirname(__FILE__).'/src/actions.php');
set_error_handler('error_handler', E_ALL);

function themler_get_base_path() {
    return 'admin/config/content/themler';
}

function themler_init() {
  $theme_name = getValue('theme');
  if (!$theme_name) {
    return;
  }

  theme_check_memory_limit(true);
  themler_enable_theme($theme_name); // enable theme 
  check_preview($theme_name); // looking for preview in the theme enabled directory
}

function themler_enable_theme($theme_name) {
    $theme_handler = \Drupal::service('theme_handler');
    $all_themes    = $theme_handler->listInfo();  // Get a list of available themes.
    $preview_name  = get_preview_theme_name($theme_name);
    if (!array_key_exists($theme_name, $all_themes) || !array_key_exists($preview_name, $all_themes)) {
        $theme_handler->install(array($theme_name, $preview_name)); // Enable themes.
        $theme_handler->rebuildThemeData(); // Rebuild, save, and return data about all currently available themes.
        drupal_flush_all_caches();
    }
}

function themler_add_manifest_version($theme_name, &$query) {
    if ($theme_name && isset($query)) {
        $version = theme_get_manifest_version($theme_name);
        if (isset($query['destination'])) {
            $desktop = theme_get_desktop_params();
            $query['destination'] .= '&ver=' . $version . $desktop;
        } else {
            $params = theme_get_desktop_params_array();
            $query['ver'] = $version;
            foreach ($params as $key => $value)
                $query[$key] = $value;
        }
    }
}

function themler_get_params() {
    $dest = \Drupal::request()->getRequestUri();
    $query = parse_url($dest, PHP_URL_QUERY);
    parse_str($query, $params);
    /*if (isset($params['username'])) unset($params['username']); // removed unset $username || $passwd for autologin
    if (isset($params['passwd'])) unset($params['passwd']);*/
    return $params;
}

function get_original_node_type($node_type) {
  $result = db_select('node', 'n')->fields('n',array('type'))->condition('type', $node_type,'=')->execute()->fetchAssoc();
  return ($result && isset($result['type'])) ? $result['type'] : false;
}

function get_templates_url($base_url, $theme_name) {
    $clean_url = get_base_clean_urls($base_url); // $base_url?q= or $base_url/
    $path      = get_preview_theme_dir(get_theme_dir($theme_name)) . '/templates/templates.php';
    $user_id   = \Drupal::currentUser()->id();
    $tokens    = array('home' => '', 'blog' => 'node', 'default' => 'user/'.$user_id, 'template404' => 'not-found');

    $result    = array();
    if (file_exists($path)) {
        require($path); // not require_once

        foreach ($templates as $type => $template) {
            foreach ($template as $t) {
                if (!empty($t['nodeType'])) {
                    $nodeType = $t['nodeType'];
                    $orig_type = get_original_node_type($nodeType);
                    $query = db_select('node', 'n')->condition('n.type', $orig_type);
                    $query->addExpression('MIN(n.nid)');
                    $min_nid = $query->execute()->fetchField();
                    if (!empty($min_nid)) {
                        $url = $clean_url . 'node/' . $min_nid . '?';
                    } else {
                        $url = ($type === 'customTemplate' ? $base_url : $clean_url . 'notemplate/' . $nodeType) . '?';
                    }
                } else {
                    $url = !empty($tokens[$type]) ? $clean_url . $tokens[$type] . '?' 
                                                  : $base_url . '?'; // home template only
                }
                $result[$t['name']] = $url . 'theme=' . $theme_name . '&template=' . $t['d'.get_major_version()];       
            }
        }
    }
    return $result;
}