/*
 * File: app/controller/Download.js
 *
 * This file was generated by Sencha Architect version 3.0.2.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Ext JS 4.2.x library, under independent license.
 * License of Sencha Architect does not include license for Ext JS 4.2.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('MyApp.controller.Download', {
	extend: 'Ext.app.Controller',

	refs: [
		{
			ref: 'downloadTemplate',
			selector: '#downloadTemplate'
		},
		{
			ref: 'downloadControls',
			selector: '#downloadControls'
		},
		{
			autoCreate: true,
			ref: 'uploadControlWindow',
			selector: '#uploadControlWindow',
			xtype: 'uploadControlWindow'
		},
		{
			ref: 'logText',
			selector: '#logText'
		},
		{
			ref: 'uploadControlsBtn',
			selector: '#uploadControlsBtn'
		},
		{
			ref: 'uploadForm',
			selector: '#uploadForm'
		},
		{
			ref: 'downloadRisk',
			selector: '#downloadRisk'
		},
		{
			ref: 'downloadRiskTemplate',
			selector: '#downloadRiskTemplate'
		},
		{
			ref: 'uploadRiskSaveBtn',
			selector: '#uploadRiskSaveBtn'
		},
		{
			ref: 'uploadRiskCancelBtn',
			selector: '#uploadRiskCancelBtn'
		},
		{
			ref: 'uploadAreaSaveBtn',
			selector: '#uploadAreaSaveBtn'
		},
		{
			ref: 'uploadAreaCancelBtn',
			selector: '#uploadAreaCancelBtn'
		},
		{
			ref: 'uploadRisksBtn',
			selector: '#uploadRisksBtn'
		},
		{
			ref: 'uploadAreasBtn',
			selector: '#uploadAreasBtn'
		},
		{
			ref: 'uploadRiskForm',
			selector: '#uploadRiskForm'
		},
		{
			ref: 'uploadAreaForm',
			selector: '#uploadAreaForm'
		},
		{
			autoCreate: true,
			ref: 'uploadRiskWindow',
			selector: '#uploadRiskWindow',
			xtype: 'uploadRiskWindow'
		},
		{
			autoCreate: true,
			ref: 'uploadAreaWindow',
			selector: '#uploadAreaWindow',
			xtype: 'uploadAreaWindow'
		},
		{
			ref: 'downloadArea',
			selector: '#downloadArea'
		},
		{
			ref: 'downloadAreaTemplate',
			selector: '#downloadAreaTemplate'
		}
	],

	init: function(application) {
		this.control({
		    '#downloadTemplate': {
		        click: function() {
		            this.download('template');
		        }
		    },
			'#downloadControls': {
		        click: function() {
		            this.download('control');
		        }
		    },
			'#downloadRiskTemplate': {
		        click: function() {
		            this.download('risk_template');
		        }
		    },
			'#downloadRisk': {
		        click: function() {
		            this.download('risk');
		        }
		    },
			'#downloadAreaTemplate': {
		        click: function() {
		            this.download('area_template');
		        }
		    },
			'#downloadArea': {
		        click: function() {
		            this.download('area');
		        }
		    },
			'#uploadControlsBtn': {
				click: function() {
		            this.getUploadControlWindow().show();
		        }
			},
			'#uploadControlCancelBtn': {
				click: function() {
		            this.getUploadControlWindow().close();
		        }
			},
			'#uploadControlSaveBtn': {
				click: function() {
		            this.uploadControl();
		        }
			},
			'#uploadRisksBtn': {
				click: function() {
		            this.getUploadRiskWindow().show();
		        }
			},
			'#uploadRiskCancelBtn': {
				click: function() {
		            this.getUploadRiskWindow().close();
		        }
			},
			'#uploadRiskSaveBtn': {
				click: function() {
		            this.uploadRisk();
		        }
			},
			'#uploadAreasBtn': {
				click: function() {
		            this.getUploadAreaWindow().show();
		        }
			},
			'#uploadAreaCancelBtn': {
				click: function() {
		            this.getUploadAreaWindow().close();
		        }
			},
			'#uploadAreaSaveBtn': {
				click: function() {
		            this.uploadArea();
		        }
			}
		});
	},

	download: function(type) {
		var iframe = document.getElementById("hiddenIFrameCurrent"+type);
		if(iframe === null) {
		    iframe = document.createElement('iframe');
		    iframe.id = "hiddenIFrameCurrent"+type;
		    iframe.style.display = 'none';
		    document.body.appendChild(iframe);
		}
		iframe.src = '../../service/download.php' + document.location.search + '&type='+type;
	},

	uploadControl: function(btn) {
		var logText = this.getLogText();
		var ctx = this;
		var check = this.checkLastUploadControl;
		logText.setValue('');
		var form = this.getUploadForm().getForm();
		if (form.isValid()) {
		    form.submit({
		        url: '../../service/upload.php?type=control',
		        params: Ext.Object.fromQueryString(document.location.search),
		        waitMsg: CCS.Translator.getText('Uploading file...'),
		        success: function(form, action) {
		            logText.setValue(CCS.Translator.getText('Upload task started...'));
					console.log('task request');
		            var task = new Ext.util.DelayedTask(check, ctx);
					console.log('task start delay');
		            task.delay(2000);
					console.log('uppload close');
					ctx.getUploadControlWindow().close();
		        },
		        failure: function(form, action) {
		            switch (action.failureType) {
		                case Ext.form.action.Action.CLIENT_INVALID:
		                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values', this.closeDialog, this);
		                    break;
		                case Ext.form.action.Action.CONNECT_FAILURE:
		                    Ext.Msg.alert('Failure', 'Ajax communication failed', this.closeDialog, this);
		                    break;
		                case Ext.form.action.Action.SERVER_INVALID:
		                    Ext.Msg.alert('Upload failed', action.result.errors[0].msg, this.closeDialog, this);
		            }
					ctx.getUploadControlWindow().close();
		        }
		    });
		}
	},

	uploadRisk: function(btn) {
		var logText = this.getLogText();
		var ctx = this;
		var check = this.checkLastUploadRisk;
		logText.setValue('');
		var form = this.getUploadRiskForm().getForm();
		if (form.isValid()) {
		    form.submit({
		        url: '../../service/upload.php?type=risk',
		        params: Ext.Object.fromQueryString(document.location.search),
		        waitMsg: CCS.Translator.getText('Uploading file...'),
		        success: function(form, action) {
		            logText.setValue(CCS.Translator.getText('Upload task started...'));
		            var task = new Ext.util.DelayedTask(check, ctx);
		            task.delay(2000);
					ctx.getUploadRiskWindow().close();
		        },
		        failure: function(form, action) {
		            switch (action.failureType) {
		                case Ext.form.action.Action.CLIENT_INVALID:
		                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values', this.closeDialog, this);
		                    break;
		                case Ext.form.action.Action.CONNECT_FAILURE:
		                    Ext.Msg.alert('Failure', 'Ajax communication failed', this.closeDialog, this);
		                    break;
		                case Ext.form.action.Action.SERVER_INVALID:
		                    Ext.Msg.alert('Upload failed', action.result.errors[0].msg, this.closeDialog, this);
		            }
					ctx.getUploadRiskWindow().close();
		        }
		    });
		}
	},

	uploadArea: function(btn) {
		var logText = this.getLogText();
		var ctx = this;
		var check = this.checkLastUploadArea;
		logText.setValue('');
		var form = this.getUploadAreaForm().getForm();
		if (form.isValid()) {
		    form.submit({
		        url: '../../service/upload.php?type=area',
		        params: Ext.Object.fromQueryString(document.location.search),
		        waitMsg: CCS.Translator.getText('Uploading file...'),
		        success: function(form, action) {
		            logText.setValue(CCS.Translator.getText('Upload task started...'));
		            var task = new Ext.util.DelayedTask(check, ctx);
		            task.delay(2000);
					ctx.getUploadAreaWindow().close();
		        },
		        failure: function(form, action) {
		            switch (action.failureType) {
		                case Ext.form.action.Action.CLIENT_INVALID:
		                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values', this.closeDialog, this);
		                    break;
		                case Ext.form.action.Action.CONNECT_FAILURE:
		                    Ext.Msg.alert('Failure', 'Ajax communication failed', this.closeDialog, this);
		                    break;
		                case Ext.form.action.Action.SERVER_INVALID:
		                    Ext.Msg.alert('Upload failed', action.result.errors[0].msg, this.closeDialog, this);
		            }
					ctx.getUploadAreaWindow().close();
		        }
		    });
		}
	},

	checkLastUpload: function(type) {
		var params = Ext.Object.fromQueryString(document.location.search);
		var logText = this.getLogText();
		logText.setValue('');
		logText.setLoading('Updating...');
		Ext.Ajax.request({
		    url: '../../service/upload.php?type='+type,
		    method: 'GET',
		    params: params,
		    success: function(response, object){
		        var poll = false;
		        var text = response.responseText;
		        var result = Ext.JSON.decode(text);
		        if (result.result.status > 1) {  // task has completed
		            logText.setValue(result.result.log);
		        } else if (result.result.status === 0) {  //task is queued
		            logText.setValue(CCS.Translator.getText('Upload task queued...'));
		            poll = true;
		        } else if (result.result.status === 1) {  //task is running
		            logText.setValue(CCS.Translator.getText('Upload task running...'));
		            poll = true;
		        }
		        logText.setLoading(false);
		        if (poll) {
		            var task = new Ext.util.DelayedTask(this.checkLastUpload(type), this);
		            task.delay(2000);
		        }
		    },
		    failure: function(response, object){
		        var text = response.responseText;
		        logText.setValue('Failed to get task status: ' + text);
		        logText.setLoading(false);
		    },
		    scope: this
		});
	},

	checkLastUploadControl: function() {
		var params = Ext.Object.fromQueryString(document.location.search);
		var logText = this.getLogText();
		logText.setValue('');
		logText.setLoading('Updating...');
		Ext.Ajax.request({
		    url: '../../service/upload.php?type=control',
		    method: 'GET',
		    params: params,
		    success: function(response, object){
		        var poll = false;
		        var text = response.responseText;
		        var result = Ext.JSON.decode(text);
		        if (result.result.status > 1) {  // task has completed
		            logText.setValue(result.result.log);
		        } else if (result.result.status === 0) {  //task is queued
		            logText.setValue(CCS.Translator.getText('Upload task queued...'));
		            poll = true;
		        } else if (result.result.status === 1) {  //task is running
		            logText.setValue(CCS.Translator.getText('Upload task running...'));
		            poll = true;
		        }
		        logText.setLoading(false);
		        if (poll) {
		            var task = new Ext.util.DelayedTask(this.checkLastUploadControl, this);
		            task.delay(2000);
		        }
		    },
		    failure: function(response, object){
		        var text = response.responseText;
		        logText.setValue('Failed to get task status: ' + text);
		        logText.setLoading(false);
		    },
		    scope: this
		});
	},

	checkLastUploadRisk: function() {
		var params = Ext.Object.fromQueryString(document.location.search);
		var logText = this.getLogText();
		logText.setValue('');
		logText.setLoading('Updating...');
		Ext.Ajax.request({
		    url: '../../service/upload.php?type=risk',
		    method: 'GET',
		    params: params,
		    success: function(response, object){
		        var poll = false;
		        var text = response.responseText;
		        var result = Ext.JSON.decode(text);
		        if (result.result.status > 1) {  // task has completed
		            logText.setValue(result.result.log);
		        } else if (result.result.status === 0) {  //task is queued
		            logText.setValue(CCS.Translator.getText('Upload task queued...'));
		            poll = true;
		        } else if (result.result.status === 1) {  //task is running
		            logText.setValue(CCS.Translator.getText('Upload task running...'));
		            poll = true;
		        }
		        logText.setLoading(false);
		        if (poll) {
		            var task = new Ext.util.DelayedTask(this.checkLastUploadRisk, this);
		            task.delay(2000);
		        }
		    },
		    failure: function(response, object){
		        var text = response.responseText;
		        logText.setValue('Failed to get task status: ' + text);
		        logText.setLoading(false);
		    },
		    scope: this
		});
	},

	checkLastUploadArea: function() {
		var params = Ext.Object.fromQueryString(document.location.search);
		var logText = this.getLogText();
		logText.setValue('');
		logText.setLoading('Updating...');
		Ext.Ajax.request({
		    url: '../../service/upload.php?type=area',
		    method: 'GET',
		    params: params,
		    success: function(response, object){
		        var poll = false;
		        var text = response.responseText;
		        var result = Ext.JSON.decode(text);
		        if (result.result.status > 1) {  // task has completed
		            logText.setValue(result.result.log);
		        } else if (result.result.status === 0) {  //task is queued
		            logText.setValue(CCS.Translator.getText('Upload task queued...'));
		            poll = true;
		        } else if (result.result.status === 1) {  //task is running
		            logText.setValue(CCS.Translator.getText('Upload task running...'));
		            poll = true;
		        }
		        logText.setLoading(false);
		        if (poll) {
		            var task = new Ext.util.DelayedTask(this.checkLastUploadArea, this);
		            task.delay(2000);
		        }
		    },
		    failure: function(response, object){
		        var text = response.responseText;
		        logText.setValue('Failed to get task status: ' + text);
		        logText.setLoading(false);
		    },
		    scope: this
		});
	}

});
