const _ = require('underscore');
const Backbone = require('backbone');
const CoreView = require('backbone/core-view');
const template = require('./dialog-view.tpl');
const FooterView = require('./footer/create-footer-view');
const NavigationView = require('builder/components/modals/add-layer/content/navigation-view');
const ListingView = require('builder/components/modals/add-layer/content/listing-view');
const TabPaneView = require('builder/components/tab-pane/tab-pane-view');
const TabPaneCollection = require('builder/components/tab-pane/tab-pane-collection');
const ViewFactory = require('builder/components/view-factory');
const renderLoading = require('builder/components/loading/render-loading');
const ErrorView = require('builder/components/error/error-view');
const CreateMapModel = require('dashboard/views/dashboard/create-map-model');
const CreateDatasetModel = require('dashboard/views/dashboard/create-dataset-model');
const VisualizationModel = require('dashboard/data/visualization-model');
const checkAndBuildOpts = require('builder/helpers/required-opts');

const DEFAULT_VIS_NAME = 'Untitled map';

const REQUIRED_OPTS = [
  'modalModel',
  'createModel',
  'configModel',
  'userModel',
  'pollingModel',
  'routerModel',
  'modalModel'
];

/**
 * Create map/dataset dialog, typically used from editor
 */
const CreateDialogView = CoreView.extend({
  className: 'Dialog-content Dialog-content--expanded',

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._initModels();
    this._initBinds();
  },

  render: function () {
    this.clearSubViews();

    this.$el.html(template());

    this._initViews();
  },

  _initModels: function () {
    this._guessingModel = new Backbone.Model({
      guessing: true
    });

    this._privacyModel = new Backbone.Model({
      privacy: this._userModel.canCreatePrivateDatasets() ? 'PRIVATE' : 'PUBLIC'
    });
  },

  _initBinds: function () {
    this.listenTo(this._createModel, 'addLayerDone', this._modalModel.destroy.bind(this._modalModel));
    this.listenTo(this._createModel, 'change:contentPane', this._onChangeContentView);
    this.listenTo(this._pollingModel, 'importByUploadData', this._modalModel.destroy.bind(this._modalModel));
  },

  _initViews: function () {
    this._navigationView = new NavigationView({
      el: this.$('.js-navigation'),
      userModel: this._userModel,
      routerModel: this._createModel.getVisualizationFetchModel(),
      createModel: this._createModel,
      tablesCollection: this._createModel.getTablesCollection(),
      configModel: this._configModel
    });
    this._navigationView.render();
    this.addView(this._navigationView);

    this._tabPaneCollection = new TabPaneCollection([
      {
        name: 'listing',
        selected: this._createModel.get('contentPane') === 'listing',
        createContentView: () => {
          return new ListingView({
            createModel: this._createModel,
            configModel: this._configModel,
            userModel: this._userModel,
            privacyModel: this._privacyModel,
            guessingModel: this._guessingModel
          });
        }
      }, {
        name: 'creatingFromScratch',
        selected: this._createModel.get('contentPane') === 'creatingFromScratch',
        createContentView: () => {
          return ViewFactory.createByHTML(
            renderLoading({
              title: _t('components.modals.add-layer.create-loading-title')
            })
          );
        }
      }, {
        name: 'loading',
        selected: this._createModel.get('contentPane') === 'loading',
        createContentView: () => {
          return ViewFactory.createByHTML(
            renderLoading({
              title: _t('components.modals.create-dialog.creating-map')
            })
          );
        }
      }, {
        name: 'addLayerFailed',
        selected: this._createModel.get('contentPane') === 'addLayerFailed',
        createContentView: () => {
          return new ErrorView({
            title: _t('components.modals.add-layer.add-layer-error')
          });
        }
      }
    ]);

    var tabPaneView = new TabPaneView({
      collection: this._tabPaneCollection
    });
    this.addView(tabPaneView);
    this.$('.js-content-container').append(tabPaneView.render().el);

    this._footerView = new FooterView({
      configModel: this._configModel,
      createModel: this._createModel,
      userModel: this._userModel,
      privacyModel: this._privacyModel,
      guessingModel: this._guessingModel
    });

    this._footerView.on('destroyModal', () => this._modalModel.destroy());

    this.addView(this._footerView);
    this.$('.js-footer').append(this._footerView.render().el);
  },

  _onChangeContentView: function () {
    var context = this._createModel.get('contentPane');
    var paneModel = _.first(this._tabPaneCollection.where({ name: context }));
    var paneModelName = paneModel.get('name');
    paneModel.set('selected', true);

    if (paneModelName === 'loading' || paneModelName === 'creatingFromScratch') {
      this._footerView.hide();
      this._navigationView.hide();
    }

    if (paneModelName !== 'listing') {
      this._navigationView.hide();
    }
  }
}, {
  setViewProperties: function (opts) {
    const mapModel = new CreateMapModel({}, {
      userModel: opts.userModel,
      configModel: opts.configModel,
      backgroundPollingModel: opts.pollingModel,
      backgroundPollingView: opts.pollingView
    });

    _.extend(this, {
      configModel: opts.configModel,
      userModel: opts.userModel,
      pollingModel: opts.pollingModel,
      pollingView: opts.pollingView,
      routerModel: opts.routerModel,
      mapModel
    });
  },

  openDialog: function (dialogDependencies, dialogOpts) {
    let createModel;

    if (dialogOpts.type === 'dataset') {
      createModel = new CreateDatasetModel({}, {
        userModel: this.userModel,
        configModel: this.configModel,
        backgroundPollingView: this.pollingView
      });
    } else {
      this.mapModel.setSelected(dialogOpts.selectedItems);
      createModel = this.mapModel;
    }

    const dialogView = new CreateDialogView({
      modalModel: dialogDependencies.modalModel,
      configModel: this.configModel,
      createModel,
      userModel: this.userModel,
      pollingModel: this.pollingModel,
      routerModel: this.routerModel
    });

    createModel.bind('datasetCreated', tableMetadata => {
      let vis;

      if (this.routerModel.model.isDatasets()) {
        vis = new VisualizationModel({ type: 'table' }, { configModel: this.configModel });
        vis.permission.owner = this.userModel;
        vis.set('table', tableMetadata.toJSON());
        window.location = vis.viewUrl(this.userModel).edit();
      } else {
        vis = new VisualizationModel({ name: DEFAULT_VIS_NAME }, { configModel: this.configModel });
        vis.permission.owner = this.userModel;
        vis.save({
          tables: [ tableMetadata.get('id') ]
        }, {
          success: m => {
            window.location = vis.viewUrl(this.userModel).edit();
          },
          error: function (e) {
            dialogDependencies.modalModel.destroy();
          }
        });
      }
    });

    dialogView.render();

    createModel.viewsReady();
    return dialogView;
  }
});

module.exports = CreateDialogView;

@@ -1663,24 +1663,60 @@
 nitViews();%0A
+    this._createModel.viewsReady();%0A
   %7D,%0A%0A  _ini
@@ -7307,65 +7307,8 @@
  %7D);
-%0A%0A    dialogView.render();%0A%0A    createModel.viewsReady();
 %0A   

fix create map from dataset list broken progress dialog