sap.ui.define(

[
  "sap/ui/core/mvc/Controller",
  "sap/m/MessageToast",
  "sap/ui/core/routing/History"
],
function(Controller, MessageToast, History) {
  "use strict";
  return Controller.extend("fivea.controller.Cultivar_Create", {
    onInit: function() {
      var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
      this._oRouter = oRouter;
    },

    onCreatePress: function() {
      var myForm = sap.ui.getCore().byId("cultivar_create_form");
      var sObjectPath = "/cultivar";
      var oView = this.getView();
      var oModel = oView.getModel();

      var oEntry = {};

      oEntry.name = this.byId("name").getValue();
      oEntry.year = this.byId("year").getValue();
      oEntry.breeder_id = this.byId("breeder_id").getValue();
      var _that = this;

      function onSuccessHandler(data) {
        oModel.refresh();
        _that.byId("name").setValue("");
        _that.byId("year").setValue("");
        _that.byId("breeder_id").setValue("");
        MessageToast.show("Create success");
        // TODO: isnt this data access OData version dependant?
        _that._oRouter.navTo("cultivar_detail", {
          id: data["results"]["0"].id
        });
      }
      function onErrorHandler() {
        MessageToast.show("Create failed");
      }

      oModel.create(sObjectPath, oEntry, {
        success: onSuccessHandler,
        error: onErrorHandler
      });
    },

    onNavBack: function() {
      var oHistory = History.getInstance();
      var sPreviousHash = oHistory.getPreviousHash();

      if (sPreviousHash !== undefined) {
        window.history.go(-1);
      } else {
        this._oRouter.navTo("cultivarList", true);
      }
    },

    inputId: "",
    inputDescrId: "",

    onBreederIdValueHelp: function(oEvent) {
      this.inputId = oEvent.getSource().getId();
      this.inputDescrId = this.inputId + "_descr";

      // create value help dialog
      if (!this._valueHelpDialog) {
        this._valueHelpDialog = sap.ui.xmlfragment(
          "fivea.view.BreederOptio",
          this
        );

        this.getView().addDependent(this._valueHelpDialog);
      }

      this._valueHelpDialog.open("");
    },

    _handleValueHelpSearch: function(evt) {
      var sValue = evt.getParameter("value");
      var oFilter = new Filter(
        "name",
        sap.ui.model.FilterOperator.Contains,
        sValue
      );
      evt
        .getSource()
        .getBinding("items")
        .filter([oFilter]);
    },

    _handleValueHelpClose: function(evt) {
      var oSelectedItem = evt.getParameter("selectedItem");
      if (oSelectedItem) {
        var IDInput = this.getView().byId(this.inputId);
        IDInput.setValue(oSelectedItem.getDescription());

        var oText = this.getView().byId(this.inputDescrId);
        oText.setText(oSelectedItem.getTitle());
      }
      evt
        .getSource()
        .getBinding("items")
        .filter([]);
    }
  });
}

);