window['content_list_model_name'] = 'discipline_teaching_plan';
window['content_list_submodel_name'] = 'teaching_plan';

$(function () {
  'use strict';

  var $unity = $('#discipline_teaching_plan_teaching_plan_attributes_unity_id');
  var $grade = $('#discipline_teaching_plan_teaching_plan_attributes_grade_id');
  var $year =$('#discipline_teaching_plan_teaching_plan_attributes_year');
  var $discipline = $('#discipline_teaching_plan_discipline_id');
  var $schoolTermType = $('#discipline_teaching_plan_teaching_plan_attributes_school_term_type_id');
  var $schoolTermContainer = $('#school-term-container');
  var $schoolTerm = $('#discipline_teaching_plan_teaching_plan_attributes_school_term_type_step_id');
  var flashMessages = new FlashMessages();
  var idContentsCounter = 1;

  function fetchDisciplines() {
    var unity_id = $unity.select2('val');
    var grade_id = $grade.select2('val');
    var year = $year.val();

    $discipline.select2('val', '');
    $discipline.select2({ data: [] });

    if (!_.isEmpty(unity_id) && !_.isEmpty(grade_id)) {
      $.ajax({
        url: Routes.search_by_grade_and_unity_disciplines_pt_br_path({
          by_unity_id: unity_id,
          by_grade: grade_id,
          year: year,
          format: 'json'
        }),
        success: handleFetchDisciplinesSuccess,
        error: handleFetchDisciplinesError
      });
    }
  };

  function handleFetchDisciplinesSuccess(data) {
    var disciplines = _.map(data.disciplines, function (discipline) {
      return { id: discipline.id, text: discipline.description };
    });

    $discipline.select2({ data: disciplines });
  };

  function handleFetchDisciplinesError() {
    flashMessages.error('Ocorreu um erro ao buscar as disciplinas da série selecionada.');
  };

  $grade.on('change', function () {
    validateMulti();
  });

  function validateMulti() {

    $.ajax({
      url: Routes.multi_grade_classrooms_pt_br_path({ format: 'json' }),
      success: function (classroom_multi) {
        if (classroom_multi) {
          return
        }
        fetchDisciplines();
      },
      error: function () {
        flashMessages.error('Ocorreu um erro ao validar se a turma é multisseriada');
      }
    });
  }

  $schoolTermType.on('change', function () {
    updateSchoolTermInput($schoolTermType, $schoolTerm, $schoolTermContainer, flashMessages);
    $('#copy_plan_info').show();
  });

  updateSchoolTermInput($schoolTermType, $schoolTerm, $schoolTermContainer, flashMessages);

  validate_attachment_size($('#discipline_teaching_plan'));

  $('#discipline_teaching_plan_teaching_plan_attributes_contents_tags').on('change', function (e) {

    if (e.val.length) {
      var uniqueId = 'customId_' + idContentsCounter++;
      var content_description = e.val.join(", ");
      if (content_description.trim().length &&
        !$('input[type=checkbox][data-content_description="' + content_description + '"]').length) {

        var html = JST['templates/layouts/contents_list_manual_item']({
          id: uniqueId,
          description: content_description,
          model_name: 'discipline_teaching_plan',
          submodel_name: 'teaching_plan'
        });

        $('#contents-list').append(html);
        $('.list-group.checked-list-box .list-group-item:not(.initialized)').each(initializeListEvents);
      } else {
        var content_input = $('input[type=checkbox][data-content_description="' + content_description + '"]');
        content_input.closest('li').show();
        content_input.prop('checked', true).trigger('change');
      }

      $('.discipline_teaching_plan_teaching_plan_contents_tags .select2-input').val("");
    }
    $(this).select2('val', '');
  });

  $('#discipline_teaching_plan_teaching_plan_attributes_objectives_tags').on('change', function (e) {
    if (e.val.length) {
      var uniqueId = 'customId_' + idContentsCounter++;
      var objective_description = e.val.join(", ");
      if (objective_description.trim().length &&
        !$('input[type=checkbox][data-objective_description="' + objective_description + '"]').length) {

        var html = JST['templates/layouts/objectives_list_manual_item']({
          id: uniqueId,
          description: objective_description,
          model_name: 'discipline_teaching_plan',
          submodel_name: 'teaching_plan'
        });

        $('#objectives-list').append(html);
        $('.list-group.checked-list-box .list-group-item:not(.initialized)').each(initializeListEvents);
      } else {
        var objective_input = $('input[type=checkbox][data-objective_description="' + objective_description + '"]');
        objective_input.closest('li').show();
        objective_input.prop('checked', true).trigger('change');
      }

      $('.discipline_teaching_plan_teaching_plan_objectives_tags .select2-input').val("");
    }
    $(this).select2('val', '');
  });

  if ($('#action_name').val() == 'show') {
    $('.list-group.checked-list-box .list-group-item').each(function () {
      $(this).off('click');
    });
  }
});

$(function () {
  $('textarea[maxLength]').maxlength();

  createSummerNote("textarea[id^=discipline_teaching_plan_teaching_plan_attributes_methodology]", {
    toolbar: [
      ['font', ['bold', 'italic', 'underline', 'clear']],
    ]
  })
  createSummerNote("textarea[id^=discipline_teaching_plan_teaching_plan_attributes_evaluation]", {
    toolbar: [
      ['font', ['bold', 'italic', 'underline', 'clear']],
    ]
  })
  createSummerNote("textarea[id^=discipline_teaching_plan_teaching_plan_attributes_references]", {
    toolbar: [
      ['font', ['bold', 'italic', 'underline', 'clear']],
    ]
  })

});
