<?php

use Drupal\Core\Entity\Entity\EntityFormMode;
use Drupal\Core\Entity\Entity\EntityViewMode;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\node\Entity\NodeType;
use Drupal\paragraphs\Entity\ParagraphsType;
use Drupal\taxonomy\Entity\Vocabulary;


/**
 * Update configs.
 */
function kamihaya_cms_recruitment_update_10001() {
  /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
  $display_repository = \Drupal::service('entity_display.repository');

  if (empty(Vocabulary::load('skill'))) {
    _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
      'taxonomy.vocabulary.skill.yml',
    ], 'install');

    _kamihaya_cms_common_save_translation_configs([
      'taxonomy.vocabulary.skill.yml',
    ], 'ja');
  }

  if (empty(Vocabulary::load('company_info'))) {
    _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
      'taxonomy.vocabulary.company_info.yml',
      'field.storage.taxonomy_term.field_company_url.yml',
      'field.field.taxonomy_term.company_info.field_company_url.yml',
    ], 'install');

    _kamihaya_cms_common_save_translation_configs([
      'taxonomy.vocabulary.company_info.yml',
      'field.field.taxonomy_term.company_info.field_company_url.yml',
    ], 'ja');
  }

  if (!empty(NodeType::load('recruitment'))) {
    $fields = [
      'field_required_skill',
      'field_welcome_skill',
    ];

    $form_display = $display_repository->getFormDisplay('node', 'recruitment');
    $view_display = $display_repository->getViewDisplay('node', 'recruitment');

    foreach($fields as $field) {
      $field_config = FieldConfig::loadByName('node', 'recruitment', $field);
      if (!empty($field_config) && $field_config->get('field_type') === 'entity_reference') {
        continue;
      }
      $form_component = $form_display->getComponent($field);
      $forn_weight = !empty($form_component) ? $form_component['weight'] : $form_display->getHeighestWeight() + 1;
      $view_component = $view_display->getComponent($field);
      $view_weight = !empty($view_component) ? $view_component['weight'] : $view_display->getHeighestWeight() + 1;

      if (!empty($field_config)) {
        $field_config->delete();
      }
      $field_storage = FieldStorageConfig::loadByName('node', $field);
      if (!empty($field_storage)) {
        $field_storage->delete();
      }
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        "field.storage.node.{$field}.yml",
        "field.field.node.recruitment.{$field}.yml",
      ], 'install');

      _kamihaya_cms_common_save_translation_configs([
        "field.field.node.recruitment.{$field}.yml",
      ], 'ja');

      foreach($fields as $field) {
        $form_display->setComponent($field, [
            'type' => 'options_select',
            'weight' => $forn_weight,
          ])
          ->save();

        $view_display->setComponent($field, [
            'label' => 'hidden',
            'type' => 'entity_reference_label',
            'weight' => $view_weight,
            'settings' => [
              'link' => FALSE,
            ],
          ])
          ->save();
      }
    }
  }

  if (!empty(ParagraphsType::load('source_code'))) {
    return;
  }

  _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
    'paragraphs.paragraphs_type.source_code.yml',
    'field.storage.paragraph.field_source_code.yml',
    'field.storage.paragraph.field_repository_url.yml',
    'field.storage.paragraph.field_score.yml',
    'field.storage.paragraph.field_coding_language.yml',
    'field.field.paragraph.source_code.field_source_code.yml',
    'field.field.paragraph.source_code.field_repository_url.yml',
    'field.field.paragraph.source_code.field_score.yml',
    'field.field.paragraph.source_code.field_coding_language.yml',
    'core.entity_view_display.paragraph.source_code.default.yml',
    'core.entity_form_display.paragraph.source_code.default.yml',
    'field.storage.user.field_source_code.yml',
    'field.field.user.user.field_source_code.yml',
  ], 'install');

  _kamihaya_cms_common_save_translation_configs([
    'paragraphs.paragraphs_type.source_code.yml',
    'field.field.paragraph.source_code.field_code.yml',
    'field.field.paragraph.source_code.field_repository_url.yml',
    'field.field.paragraph.source_code.field_score.yml',
    'field.field.paragraph.source_code.field_coding_language.yml',
    'field.field.user.user.field_source_code.yml',
  ], 'ja');

  $display_repository->getFormDisplay('user', 'user')
    ->removeComponent('field_source_code')
    ->save();

  $display_repository->getViewDisplay('user', 'user')
    ->removeComponent('field_source_code')
    ->save();
}

/**
 * Update configs.
 */
function kamihaya_cms_recruitment_update_10002() {
  /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
  $display_repository = \Drupal::service('entity_display.repository');

  // Delete field_source_code from source_code paragraph type.
  if (!empty(ParagraphsType::load('source_code'))) {
    $field_config = FieldConfig::loadByName('paragraph', 'source_code', 'field_source_code');
    if (!empty($field_config)) {
      $field_config->delete();
    }
    $field_storage = FieldStorageConfig::loadByName('paragraph', 'source_code');
    if (!empty($field_storage)) {
      $field_storage->delete();
    }
  }

  if (!empty(ParagraphsType::load('skill'))) {
    $field_config = FieldConfig::loadByName('paragraph', 'skill', 'field_skill');
    $form_display = $display_repository->getFormDisplay('paragraph', 'skill');
    $form_weight = 0;
    $view_display = $display_repository->getViewDisplay('paragraph', 'skill');
    $view_weight = 0;
    if (!empty($field_config) && $field_config->get('field_type') !== 'entity_reference') {
      $form_component = $form_display->getComponent('field_skill');
      $form_weight = !empty($form_component) ? $form_component['weight'] : $form_display->getHeighestWeight() + 1;
      $view_component = $view_display->getComponent('field_skill');
      $view_weight = !empty($view_component) ? $view_component['weight'] : $view_display->getHeighestWeight() + 1;

      if (!empty($field_config)) {
        $field_config->delete();
      }
      $field_storage = FieldStorageConfig::loadByName('paragraph', 'field_skill');
      if (!empty($field_storage)) {
        $field_storage->delete();
      }
    }
    _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
      "field.storage.paragraph.field_skill.yml",
      "field.field.paragraph.skill.field_skill.yml",
    ], 'install');

    _kamihaya_cms_common_save_translation_configs([
      "field.field.paragraph.skill.field_skill.yml",
    ], 'ja');

    $form_display->setComponent('field_skill', [
      'type' => 'options_select',
      'weight' => $form_weight,
    ])
    ->save();

    $view_display->setComponent('field_skill', [
      'label' => 'inline',
      'type' => 'entity_reference_label',
      'weight' => $view_weight,
      'settings' => [
        'link' => FALSE,
      ],
    ])
    ->save();
  }

  // Set field_first_name_kana and field_last_name_kana of user entity to not required.
  foreach(['field_first_name_kana', 'field_last_name_kana'] ?: [] as $field) {
    $field_config = \Drupal::configFactory()->getEditable("field.field.user.user.{$field}");
    if (empty($field_config)) {
      return;
    }
    $field_config->set('required', FALSE);
    $field_config->save(TRUE);
  }

  // Add filed_company to user entity.
  $field_storage = FieldStorageConfig::loadByName('user', 'field_company');
  if (empty($field_storage)) {
    _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
      "field.storage.user.field_company.yml",
      "field.field.user.user.field_company.yml",
    ], 'install');
    _kamihaya_cms_common_save_translation_configs([
      "field.field.user.user.field_company.yml",
    ], 'ja');
  }

  // Create recruitment_register form mode to user entity.
  $form_modes = [
    'recruitment_register',
    'applicant_edit',
    'recruiter_edit',
  ];
  foreach ($form_modes as $mode) {
    $form_mode = \Drupal::entityTypeManager()->getStorage('entity_form_mode')->load("user.{$mode}");
    if (empty($form_mode)) {
      $form_mode = EntityFormMode::create([
        'id' => "user.{$mode}",
        'targetEntityType' => 'user',
        'label' => t(ucfirst(str_replace('_', ' ', $mode))),
        'status' => TRUE,
      ]);
      $form_mode->save();
    }

    $form_display = $display_repository->getFormDisplay('user', 'user', $mode);
    if (empty($form_display) || $form_display->isNew()) {
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        "core.entity_form_display.user.user.{$mode}.yml",
      ], 'install');
    }
  }

  // Create recruitment view mode to company_info taxonomy.
  if (!empty(Vocabulary::load('company_info'))) {
    $view_mode = \Drupal::entityTypeManager()->getStorage('entity_view_mode')->load('taxonomy_term.recruitment');
    if (empty($view_mode)) {
      $view_mode = EntityViewMode::create([
        'id' => 'taxonomy_term.recruitment',
        'targetEntityType' => 'taxonomy_term',
        'label' => t('Recruitment'),
        'status' => TRUE,
      ]);
      $view_mode->save();
    }

    $view_display = $display_repository->getViewDisplay('taxonomy_term', 'company_info', 'recruitment');
    if (empty($view_display) || $view_display->isNew()) {
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        'core.entity_view_display.taxonomy_term.company_info.recruitment.yml',
      ], 'install');
    }
  }

  // Create job match list view mode to recruitment node.
  if (!empty(NodeType::load('recruitment'))) {
    $view_mode = \Drupal::entityTypeManager()->getStorage('entity_view_mode')->load('node.job_match_list');
    if (empty($view_mode)) {
      $view_mode = EntityViewMode::create([
        'id' => 'node.job_match_list',
        'targetEntityType' => 'node',
        'label' => t('Job match list'),
        'status' => TRUE,
      ]);
      $view_mode->save();
    }

    $view_display = $display_repository->getViewDisplay('node', 'recruitment', 'job_match_list');
    if (empty($view_display) || $view_display->isNew()) {
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        'core.entity_view_display.node.recruitment.job_match_list.yml',
      ], 'install');
    }
  }

  // Create or uidate job list views.
  _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
    'views.view.job_list.yml',
    'views.view.matching_result_dashboard.yml',
  ], 'install');
}


/**
 * Update configs.
 */
function kamihaya_cms_recruitment_update_10003() {
  /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
  $display_repository = \Drupal::service('entity_display.repository');

  if (!empty(ParagraphsType::load('source_code'))) {
    $field_config = FieldConfig::loadByName('paragraph', 'source_code', 'field_score');
    if (!empty($field_config) && $field_config->get('field_type') !== 'decimal') {
      // Change field_score type to decimal.
      $form_display = $display_repository->getFormDisplay('paragraph', 'source_code');
      $view_display = $display_repository->getViewDisplay('paragraph', 'source_code');

      if (!empty($field_config)) {
        $field_config->delete();
      }
      $field_storage = FieldStorageConfig::loadByName('paragraph', 'field_score');
      if (!empty($field_storage)) {
        $field_storage->delete();
      }
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        "field.storage.paragraph.field_score.yml",
        "field.field.paragraph.source_code.field_score.yml",
      ], 'install');

      _kamihaya_cms_common_save_translation_configs([
        "field.field.paragraph.source_code.field_score.yml",
      ], 'ja');
    }

    // Disable link title of field_repository_url on source_code paragraph type.
    $field_config = \Drupal::configFactory()->getEditable("field.field.paragraph.source_code.field_repository_url");
    $field_config->set('settings.title', DRUPAL_DISABLED);
    $field_config->save(TRUE);
  }

  // Make field_skill required on skill paragraph type.
  if (!empty(ParagraphsType::load('skill'))) {
    $field_config = FieldConfig::loadByName('paragraph', 'skill', 'field_skill');
    if (!empty($field_config)) {
      $field_config->set('required', TRUE);
      $field_config->save(TRUE);
    }
  }

  // Create applicant list view mode to recruitment node.
  if (!empty(NodeType::load('recruitment'))) {
    $view_mode = \Drupal::entityTypeManager()->getStorage('entity_view_mode')->load('node.applicant_list');
    if (empty($view_mode)) {
      $view_mode = EntityViewMode::create([
        'id' => 'node.applicant_list',
        'targetEntityType' => 'node',
        'label' => t('Applicant list'),
        'status' => TRUE,
      ]);
      $view_mode->save();
    }
    $view_display = $display_repository->getViewDisplay('node', 'recruitment', 'applicant_list');
    if (empty($view_display) || $view_display->isNew()) {
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        'core.entity_view_display.node.recruitment.applicant_list.yml',
      ], 'install');
    }
  }

  if (!empty(ParagraphsType::load('source_code'))) {
    $view_mode = \Drupal::entityTypeManager()->getStorage('entity_view_mode')->load('paragraph.applicant_list');
    if (empty($view_mode)) {
      $view_mode = EntityViewMode::create([
        'id' => 'paragraph.applicant_list',
        'targetEntityType' => 'paragraph',
        'label' => t('Applicant list'),
        'status' => TRUE,
      ]);
      $view_mode->save();
    }
    $view_display = $display_repository->getViewDisplay('paragraph', 'source_code', 'applicant_list');
    if (empty($view_display) || $view_display->isNew()) {
      _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
        'core.entity_view_display.paragraph.source_code.applicant_list.yml',
      ], 'install');
    }
  }

  // Create applicant search view.
  _kamihaya_cms_common_change_configs('kamihaya_cms_recruitment', [
    'views.view.applicant_search.yml',
  ], 'install');

  // Change the path of matching_result_dashboard view.
  $view = \Drupal::entityTypeManager()->getStorage('view')->load('matching_result_dashboard');
  $display =& $view->getDisplay('page_1');
  $display['display_options']['path'] = 'job/matching_result';
  $view->save();
}
