define([
  'core/js/adapt'
], function (Adapt) {

  var AdaptView = Backbone.View.extend({

    attributes: function () {
      return {
        "data-adapt-id": this.model.get('_id')
      };
    },

    initialize: function () {
      this.listenTo(Adapt, 'remove', this.remove);
      this.listenTo(this.model, {
        'change:_isVisible': this.toggleVisibility,
        'change:_isHidden': this.toggleHidden,
        'change:_isComplete': this.onIsCompleteChange
      });
      this.model.set({
        '_globals': Adapt.course.get('_globals'),
        '_isReady': false
      });
      this._isRemoved = false;

      if (Adapt.location._currentId === this.model.get('_id')) {
        Adapt.parentView = this;
      }

      this.preRender();
      this.render();
      this.setupOnScreenHandler();
    },

    preRender: function () {
      

    },
    postRender: function () {
      var $parentContainer = this.$(this.constructor.childContainer);
      // if ($($parentContainer).is('.js-children')) {
      //   this.addMenuChildrens();
      // } else {
        this.addChildren();
      // }

    },

    render: function () {
      Adapt.trigger(this.constructor.type + 'View:preRender', this);

      var data = this.model.toJSON();
      data.view = this;
      var template = Handlebars.templates[this.constructor.template];
      this.$el.html(template(data));

      Adapt.trigger(this.constructor.type + 'View:render', this);

      _.defer(function () {
        // don't call postRender after remove
        if (this._isRemoved) return;

        this.postRender();
        Adapt.trigger(this.constructor.type + 'View:postRender', this);
      }.bind(this));

      return this;
    },

    setupOnScreenHandler: function () {
      
      var onscreen = this.model.get('_onScreen');

      if (!onscreen || !onscreen._isEnabled) return;

      this.$el
        .addClass('has-animation')
        .addClass(onscreen._classes + '-before');

      this.$el.on('onscreen.adaptView', function (e, m) {

        if (!m.onscreen) return;

        var minVerticalInview = onscreen._percentInviewVertical || 33;

        if (m.percentInviewVertical < minVerticalInview) return;

        this.$el.addClass(onscreen._classes + '-after' || 'onscreen').off('onscreen.adaptView');

      }.bind(this));
    }, 

    addMenuChildrens: function () {
      var nthChild = 0;
      var children = this.model.getChildren();
      var $parentContainer = this.$(this.constructor.childContainer);
      var models = children.models;

      var menuAccordion = [];
      this.childViews = {};
      var menuGroups = models.map(function(v){return (v.attributes.groupId)}).filter(function(v,i,ar){return (ar.indexOf(v)===i)});
      menuGroups.forEach(function (ele){
        menuAccordion.push(models.filter(function(v){return v.attributes.groupId===ele}))
      });

      var ref = this;
      var lockPath = 'assets/menu/B';
      var altText = {
        menuExpend:Adapt.course.attributes._globals._accessibility._ariaLabels.menuEpend || "",
        menuCollapsed:Adapt.course.attributes._globals._accessibility._ariaLabels.menuCollepse || ""
      }
      menuAccordion.forEach(function(ele,inx){
        var container = $('<div class="menu-accordion-container" />'); 
        container.append("<div title='"+(inx===0?altText.menuCollapsed:altText.menuExpend)+"'  class='menu-accordion-heading "+(inx===0?'open':'close')+"' style='background-color:"+ele[0].attributes.color+(ele[0].attributes.textColor?";color:"+ele[0].attributes.textColor:"")+"'>"+ele[0].attributes.groupTitle+"<span class='icon icon-controls-"+(i===0?'up':'down')+"'></sapn></div>")
        var panel = $("<div class='menu-accordion-panel' style='display:"+(i===0?'block':'none')+";'/>");

        if(inx === 0){
          $(".key-"+(inx+1)).css('background-image',"url('" + lockPath + "" + inx + "_1.png')").addClass('unlocked');
        }
        for (var i = 0, len = ele.length; i < len; i++) {
          var model = ele[i];
          nthChild++;

          if(model.get('_isComplete')){
            $(".key-"+(nthChild)).css('background-image',"url('" + lockPath + "" + (nthChild-1) + "_1.png')").addClass('unlocked');
          }
          model.set("_nthChild", nthChild);
          
          var ViewModelObject = ref.constructor.childView || Adapt.componentStore[model.get("_component")];
          var ChildView = ViewModelObject.view || ViewModelObject;
          var childView = new ChildView({ model: model });
          ref.childViews[model.get('_id')] = childView;

          $('.key-'+(nthChild)).attr("title",($('.key-'+(nthChild)).hasClass('unlocked')?"Unlocked":"Locked")+": "+model.attributes.title);

          var isPrevCompleted =  models[(nthChild-2>0?nthChild-2:0)].get('_isComplete');
          isPrevCompleted = nthChild===1?true:isPrevCompleted;
          // $(container).find('.menu-accordion-heading').attr('title',altText.menuExpend);
          if(isPrevCompleted) {
            childView.$('.icon').removeClass('icon-padlock-locked').addClass('icon-padlock-unlocked');
            childView.$('button').removeClass('user-select-none').addClass('selected');
            // console.log(nthChild,'++++++++++++++++++++++++++++')
            $(".key-"+(nthChild)).css('background-image',"url('" + lockPath + "" + (nthChild-1) + "_1.png')").addClass('unlocked');
            $(container).find('.menu-accordion-heading').removeClass('close').addClass('open');
            $(container).find('.menu-accordion-heading .icon').removeClass('icon-controls-down').addClass('icon-controls-up');
            // $(container).find('.menu-accordion-heading').attr('title',altText.menuCollapsed);
            panel.css('display','block');
            // $('.menu-accordion-heading').length && $($('.menu-accordion-heading')[i-1]).click();
          }

          // var isThisCompleted = model.get('_isComplete');
          // if(isPrevCompleted){
            
          // }
          panel.append(childView.$el);
        }

        $parentContainer.append(container.append(panel));
      });
     
    },

    addChildren: function () {
      var nthChild = 0;
      var children = this.model.getChildren();
      var models = children.models;
      this.childViews = {};
      for (var i = 0, len = models.length; i < len; i++) {
        var model = models[i];
        if (!model.get('_isAvailable')) continue;

        nthChild++;
        model.set("_nthChild", nthChild);

        var ViewModelObject = this.constructor.childView || Adapt.componentStore[model.get("_component")];
        var ChildView = ViewModelObject.view || ViewModelObject;

        if (!ChildView) {
          throw 'The component \'' + models[i].attributes._id + '\'' +
          ' (\'' + models[i].attributes._component + '\')' +
          ' has not been installed, and so is not available in your project.';
        }

        var $parentContainer = this.$(this.constructor.childContainer);

        var childView = new ChildView({ model: model });

        this.childViews[model.get('_id')] = childView;

        $parentContainer.append(childView.$el);
      }
    },

    findDescendantViews: function (isParentFirst) {
      var descendants = [];
      this.childViews && _.each(this.childViews, function (view) {
        if (isParentFirst) descendants.push(view);
        var children = view.findDescendantViews && view.findDescendantViews(isParentFirst);
        if (children) descendants.push.apply(descendants, children);
        if (!isParentFirst) descendants.push(view);
      });
      return descendants;
    },

    setReadyStatus: function () {
      this.model.set('_isReady', true);
    },

    setCompletionStatus: function () {      
      if (this.model.get('_isVisible')) {
        this.model.set({
          '_isComplete': true,
          '_isInteractionComplete': true
        });
      }
    },

    resetCompletionStatus: function (type) {
      if (!this.model.get("_canReset")) return;

      var descendantComponents = this.model.findDescendantModels('components');
      if (descendantComponents.length === 0) {
        this.model.reset(type);
      } else {
        _.each(descendantComponents, function (model) {
          model.reset(type);
        });
      }
    },

    preRemove: function () { },

    remove: function () {

      this.preRemove();
      this._isRemoved = true;

      Adapt.wait.for(function (end) {

        this.$el.off('onscreen.adaptView');
        this.model.setOnChildren('_isReady', false);
        this.model.set('_isReady', false);
        Backbone.View.prototype.remove.call(this);

        end();
      }.bind(this));

      return this;
    },

    setVisibility: function () {
      var visible = 'u-visibility-hidden';
      if (this.model.get('_isVisible')) {
        visible = '';
      }
      return visible;
    },

    toggleVisibility: function () {
      if (this.model.get('_isVisible')) {
        return this.$el.removeClass('u-visibility-hidden');
      }
      this.$el.addClass('u-visibility-hidden');
    },

    setHidden: function () {
      var hidden = '';
      if (this.model.get('_isHidden')) {
        hidden = 'u-display-none';
      }
      return hidden;
    },

    toggleHidden: function () {
      if (!this.model.get('_isHidden')) {
        return this.$el.removeClass('u-display-none');
      }
      this.$el.addClass('u-display-none');
    },

    onIsCompleteChange: function (model, isComplete) {
      this.$el.toggleClass('is-complete', isComplete);
      if(model.get('_type')==='block'){
        Adapt.trigger('chocho:phokho',model);
      }
    },

    getChildViews: function () {
      return this.childViews;
    }

  }, {
    className: ''
  });

  return AdaptView;

});
