____USER.refresh();

function drawCustomSelectChooserElementValue(header, res) {
    let container = h.div("search_item");
    if (utils.e(header.getField(), "status")) {

        if (res == null) {
            return container.text("&nbsp;", false)
        }

        if (!utils.isEmpty(res.additional.icon)) {
            container.add(h.img(res.additional.icon, Environment.defaultIconSize).wh(16));
        }

        if (!utils.isEmpty(res.additional.color)) {
            container.get().style.background = res.additional.color;
        }

        return container.andText(res.value, false);


    } else {
        if (res.additional == null) {
            return container.andText(res.value, false);
        }
        if (!utils.isEmpty(res.additional)) {
            if (!utils.isEmpty(res.additional)) {
                container.add(h.img(res.additional, Environment.defaultIconSize).wh(16));
            }
            return container.andText(res.value, false);
        }
        return null;
    }
}

class NameFieldWithSimilarIssue extends InputField{
  
  static CLASS = "form-name-field__info-";

  static SHOW_CHECKBOX_SETTINGS = "showSimilarIssue"

  #inputWrapper;
  #holder;
  #similarContainer = h.div(NameFieldWithSimilarIssue.CLASS + "wrapper").cl('issue');

  #groupCheckbox;
  #showCheckbox;

  constructor(field) {
    super(field);
  } 

  setValue(value) {
    let text = ''
    if(value){
      text = value[this.getField().getField()];
    }
    this.#holder.text(text, false);
  }

  create(value) {
    let rowWrapper = h.div('row__wrapper')
    let div = this.createContainer().appendTo(rowWrapper);

    let el = this.createWebObject().inputFunc(this.inputListener);
    this.#holder = el;

    if (this.toShowPlaceHolder()) {
        el.placeHolder(this.getPlaceHolder(), false);
    }

    this.markElementsRequired(el, div);

    this.setThisValue(el, value);

    if (value != null) {
        el.text(value[this.getField().getField()], false);
    }

    this.showLabel(div);
    this.addElementToInput(div, el);

    dom.errorPlate(this.getField().getField()).appendTo(rowWrapper);
    
    div.clIf(utils.e(this.getField().getType(), dom.HIDDEN), dom.HIDDEN);

    this.drawInfoRow();

    return rowWrapper;
}

  addElementToInput(div, el) {

    this.#inputWrapper = h.div("text-field__input-wrapper").add(el);

    div.add(this.#inputWrapper);
  }

  drawInfoRow() {

    const showCheckboxId = "more-info-checkbox";

    const allGroupCheckBoxId = "all-group-name-search";

    let row = h.div(NameFieldWithSimilarIssue.CLASS + "row");

    this.#showCheckbox = h.input("checkbox").attr("checked", "").appendTo(row).id(showCheckboxId).change(this.showInputListener);

    h.label(showCheckboxId, "", false).appendTo(row);

    row.add(h.span(NameFieldWithSimilarIssue.CLASS + "span").text("issuecontroller.issueform.checkbox.show.similar.issues"));

    this.#groupCheckbox = h.input("checkbox").attr("checked", "").appendTo(row).id(allGroupCheckBoxId).change(this.groupCheckboxListener);
    
    h.label(allGroupCheckBoxId, "", false).appendTo(row);
    
    h.span(NameFieldWithSimilarIssue.CLASS + "span").text("issuecontroller.issueform.checkbox.search.in.all.groups").appendTo(row)

    this.#inputWrapper.add(row).add(this.#similarContainer);

    this.checkShowCheckbox();
  }

  checkShowCheckbox(){
    let isChecked = PersonalSettings.getSetting(NameFieldWithSimilarIssue.SHOW_CHECKBOX_SETTINGS);

    _e(isChecked, "true") ? this.#showCheckbox.attr("checked", '') : this.#showCheckbox.setA("checked", null);
  }

  groupCheckboxListener = (el, ev) => {
    this.drawInfoBlock(this.#holder.val())
  }

  showInputListener = (el) => {
    if(el.checked()) {
      PersonalSettings.setSetting(NameFieldWithSimilarIssue.SHOW_CHECKBOX_SETTINGS, "true");

      this.#similarContainer.appendTo(this.#inputWrapper);

      this.drawInfoBlock(this.#holder.val());
    } else {
      PersonalSettings.setSetting(NameFieldWithSimilarIssue.SHOW_CHECKBOX_SETTINGS, "false");

      this.#similarContainer.remove();
    }
  }

  getsimilarRow(data){
    return  dom.redirectToViewPage("issue", data.id).cl(NameFieldWithSimilarIssue.CLASS + "similar")
    .addIf(data.icon,
      h.img(data.icon, Environment.defaultIconSize)
    ).add(
      h.span(NameFieldWithSimilarIssue.CLASS + "issue").text(data.name, false)
    )
  }

  search = _.debounce((text) => this.drawInfoBlock(text), 550);

  inputListener = (el) => { 

    if(!el.value) {
      this.#similarContainer.text(null);

      return;
    }

    if(this.#showCheckbox.checked()){
      this.search(el.value);
    } 
  }

  read(){
    return this.#holder.val()
  }

  drawInfoBlock(value){

    if(value){
      let payload = {
        "searchText": value,
        "limit": 10,
        "group": this.#groupCheckbox.checked() ? 0 : Number(cache.get(Group.GROUP_SELECTED))
      }
  
      Executor.runPostWithPayload(Environment.dataApi + "/api/v2/flaw/issue/similar", (data) => {

        if(data.content.length){
          this.#similarContainer.text(null);
  
          _.each(data.content, (item) => {
            this.#similarContainer.add(this.getsimilarRow(item))
          })
        } else this.#similarContainer.text(null)
  
      }, payload, (e) => {})
    }
    }
}

function getCustomRenderer(field, parent) {
    if (_.e(field.getType(), 'connection')) {
      return new ConnectionChooser(field).setParent(parent);
  }

    if (_.e(field.getField(), 'name')) { 
      if(_e(field.getOptions().getRoot(),'/api/v2/flaw/issue')){
        return new NameFieldWithSimilarIssue(field);
      }
      
  }
}

function isClearItemAllowed(header) {
    return !_.e(header.getField(), Group.GROUP_FIELD);
}

function transformCustomData(header, dataTo, dataFrom) {
    if (utils.e(header, "status")) {
        dataTo.additional = {
            "icon": dataFrom.icon,
            "color": dataFrom.color
        }
    }

}

function drawCustomSelectChooserElement(header, res, data) {
    let container = h.div("search_item");
    if (utils.e(header.getField(), "status")) {

        if (res == null) {
            return container.text("&nbsp;", false)
        }

        if (!utils.isEmpty(res.icon)) {
            container.add(h.img(res.icon, Environment.defaultIconSize).wh(16));
        }

        if (!utils.isEmpty(res.color)) {
            container.get().style.background = res.color;
        }

        return container.andText(res.name, false);


    } else {
        if (!utils.isEmpty(res.icon)) {
            if (!utils.isEmpty(res.icon)) {
                container.add(h.img(res.icon).wh(16));
            }
            return container.andText(res[header.getData().searchField], false);
        }
        return null;
    }
}

function closeMenu1(obj) {
    obj.style.display = "none";
}

function showMenu(obj, parent) {
    let bounds = parent.getBoundingClientRect();
    obj.style.position = "fixed";
    obj.style.left = 108;
    obj.style.top = parseInt(bounds.top);
    obj.style.display = "block";
}

function drawMyGroups(where, grClass = null) {
    Group.withMyGroups((groups) => {
      var selectedGroup = cache.get(Group.GROUP_SELECTED);
        let w = h.fromId(where).text(null);
        if (w) {
            utils.each(groups.content, (group) => { 

              var isSelected = _e(selectedGroup, group.id);

                let divIcon = h.divImg(group.icon, Environment.defaultIconSize).cl("menu-icon");
                h.div("group").clIf(grClass != null, grClass).clIf(isSelected, "selected__group").cl('drag_target').id(group.id)
                    .add(divIcon)
                    .add(h.span("title_" + grClass, group.name)).pointer().click((x) => {
                    Group.selectGroup(group, x);
                    document.location.href = Environment.self + "/pages/group/view?id=" + group.id;
                }).appendTo(w)
                .dragOver((e)=>{
                    h.from(e.currentTarget).cl('bgc_green');
                    h.from(e.currentTarget).rcl('bgc_white');
                    e.preventDefault();                   
                })
                .dragDrop((e)=>{
                   let issueId = cache.get('dragId');
                   h.from(e.currentTarget).cl('bgc_white');
                   h.from(e.currentTarget).rcl('bgc_green');
                   if(_.notNull(issueId) && _.notNull(e.currentTarget.id)){
                    let path = `${Environment.dataApi}/api/v2/flaw/issue/move/${issueId}/${e.currentTarget.id}?condition=2`;
                        Executor.runPost(path, function (data) {
                           dom.successMessage();
                        })
                   }
                })
                .dragLeave((e)=>{
                    h.from(e.currentTarget).cl('bgc_white');
                    h.from(e.currentTarget).rcl('bgc_green');
                })
            })
        }
    })
}

drawMyGroups(Group.GROUPS_PANEL_ID, "menu-item");

function changeSearchPath(path, searchName) {

    if (is(searchName, "status") || is(searchName, "prio") || is(searchName, "issue")
        || is(searchName, "epic") || is(searchName, "solution") || is(searchName, "link")
        || is(searchName, "project") || is(searchName, "story") || is(searchName, "sprint")) {

        path += "&ids=" + Group.getTempValue();

    }
    return path;
}

function is(searchName, of) {
    return searchName.toLowerCase().indexOf(of) != -1 && _.notNull(cache.get(Group.GROUP_SELECTED));
}



buildLanguagesPanel();

function getLanguages(panel) {

  let payload = new MagicRequest();

    payload.query[0] =   {
      "field": "active",
      "value": true,
      "searchName": "active",
      "dataType": "object_chooser",
      "type": "="
    }

  panel.text(null)

  Executor.runPostWithPayload(Environment.dataApi + '/api/v2/flaw/language/root/fetch/data/', (data) => {

    _.each(data.content, (item) => {

      let link = h.tag("a").click(() => {
        ____USER.changeLanguage(item.code)
      })

      link.add(h.div('language').text(item.name, false).cl("lang_" + item.code));

      panel.add(link);
    });

    
  }, payload)
}

async function buildLanguagesPanel(){

  const panelClass = ".dropdown-content22-language-menu";

  let check = () => {
    if(document.querySelector(".dropdown-content22-language-menu")){
      return document.querySelector(".dropdown-content22-language-menu")
    } return undefined
  }

  dom.waitForItem(check, () => {
    getLanguages(h.fromFirst(panelClass))
  })
}