/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-h2-plugin
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
var EntaxyH2;
(function (EntaxyH2) {
    EntaxyH2.log.debug("loading console");
	
    EntaxyH2._module
    .component('entaxyH2Console', {
        template: `<iframe id="h2consoleFrame" src='/h2console/h2console/' style="width: 100%; height: 100%; overflow: scroll; border: none"></iframe>`,
        controller: EntaxyH2ConsoleController
    })
    .name;
	
	function EntaxyH2ConsoleController($scope, $element, $location, workspace, localStorage, jolokia) {
        'ngInject';
        var ctrl = this;
        this.$location = $location;
		entaxyH2location = this.$location;
		entaxyH2ctrl = ctrl;
		entaxyH2scope = $scope; 
		entaxyH2element = $element;

		var iFrame = $element.context.childNodes[0]; 

		this.prepareUrl = (function (){
			var path = workspace.selection.entries.path;
			var resultPath = path;
			if ((path.at(1)=="_") && (path.at(2)=="/")) {
				resultPath = path.substring(0,1) + ":" + path.substring(2);
			}
			return "jdbc:h2:" + resultPath; 
		}).bind(this);

		this.onLoad = (function() {
			if (iFrame.contentDocument.getElementById('login')){
				var form = iFrame.contentDocument.getElementById('login');
				
				// set correct connection url
				form.getElementsByTagName('input')
					.namedItem("url").value = this.prepareUrl();
				
				// add href for opening in new window
				var p = form.getElementsByTagName("p").item(0);
				var space = angular.element('<span>&nbsp;&nbsp;</span>');
				var link = angular.element('<a href="/h2console/h2console" target="_blank">[Open in new window]</a>');
				angular.element(p).append(space);
				angular.element(p).append(link);
			}
		}).bind(this);
	
	
		iFrame.onload = this.onLoad;
		
	}
	EntaxyH2ConsoleController.$inject = ['$scope', '$element', '$location', 'workspace', 'localStorage', 'jolokia'] 
	
})(EntaxyH2 || (EntaxyH2 = {}));
