/*
 * Licensed Materials - Property of IBM
 *
 * IBM Cognos Products: SHARE
 *
 * (C) Copyright IBM Corp. 2015, 2019
 *
 * US Government Users Restricted Rights - Use, duplication or disclosure
 * restricted by GSA ADP Schedule Contract with IBM Corp.
 */

define([
	'underscore',
	'bi/glass/app/ContentView',
	'bi/content_apps/utils/GlassContextHelper',
	'jquery',
	'q',
	'dashboard-analytics/preview/LiveWidgetPreview'
], function (_, View, GlassContextHelper, $, Q, lWidget) {
	var MESSAGE_VERSION = '1.0.0';

	var mobileView = View.extend({
		lw: null,
		widgetSpec: {},

		init: function (options) {
			this.widgetSpec = {};

			mobileView.inherited('init', this, arguments);

			this.data = {};

			$.extend(this, options);
		},

		postMessage : function({ name, data }){
			window.ReactNativeWebView.postMessage(this.createMessage({ name, data }));
		},

		createMessage: function({ name, data }){
			const message = JSON.stringify({
				name,
				data,
				version: MESSAGE_VERSION
			});
			return message;
		},

		onResize: function(){
			this.lw.resize();
			setTimeout(()=>{
				if(this.isVisHorizontal){
					this.lw.widget._currVis.viprWidget.setLegendPosition('right');
				}else{
					this.lw.widget._currVis.viprWidget.setLegendPosition('top');
				}
				this.lw.widget._currVis.viprWidget.render();
			// will working hard to remove the timeout
			},300);

		},

		generateThumbnail: function(widget){
			widget.generateThumbnail({
				size:{
					width:350,
					height:350
				}
			}).then(data=>{
				this.postMessage({
					name:'thumbnailSvg',
					data:data.thumbnail
				});
			});
		},


		renderVis: function(widgetSpec){
			if(widgetSpec){

				this.widgetSpec = widgetSpec;
				this.widgetSpec.properties = [
					{
						id: 'widget.legend.font',
						value: '14px'
					}
				];
				if(this.isVisHorizontal){
					this.widgetSpec.properties.push({
						id: 'widget.legend.position',
						value: 'right'
					});
				}

				$('.ca-mobile-live-widget').detach();
				$('head').append(`<style>
										*{
											box-sizing:border-box;
										}
										body,html{
											width:100%;
											height:100%
											margin:0;
											padding:0;
										}
										.ca-mobile-live-widget{
											width:100vw;
											height:100vh;
											z-index:999;
											display: flex;
											flex-direction: column;
										}
										.ca-mobile-live-widget__title{
											padding-top:16px;
											padding-bottom:16px;
											padding-left:16px;
											font-size: 18px;
											line-height: 14px;
											font-weight: bold;
											color:#343334;
										}
										.ca-mobile-live-widget__content{
											flex: auto 1;
										}
								</style>`);
				$('body').append(`
							<div class="ca-mobile-live-widget" > 
								<div class="ca-mobile-live-widget__title">
									${this.title} 
								</div>
								<div class="ca-mobile-live-widget__content">
								</div>
							</div>`);


				this.lw = new lWidget({
					glassContext: this.glassContext,
					enableClick: true,
					enablePanAndZoom: true,
					enableHover: true,
					node: $('.ca-mobile-live-widget')[0],
					spec: widgetSpec
				});

				this.lw.render()
					.then(()=>{
						if(this.lw.widget.isRendered){
							this.generateThumbnail(this.lw.widget);
							window.addEventListener('resize',this.onResize.bind(this));
						}
					})
					.catch(err=>{
						console.warn('failed to render visualizaion:', err);
					});
			}
		},

		destroy: function(){
			this.lw.destroy();
			window.removeEventListener('resize');
		},

		onMessage: function(event){
			const message = JSON.parse(event.data);

			this.readMessage(message);
		},

		readMessage: function(message){
			// for backward compatible cuz the change from ca-mobile-client not merged yet.
			if(message.version === 'test'){
				if(message.name === 'title'){
					this.title = message.data;
				}else if(message.name === 'orientation'){
					if( message.data === 'landscape'){
						this.isVisHorizontal = true;
					}else if( message.data === 'portrait'){
						this.isVisHorizontal = false;
					}
				}
			}else{
				this.source = message;
				this.renderVis(message);
			}
		},

		open: function(/* context, options */){
			this.glassContext = __glassAppController.glassContext; // eslint-disable-line no-undef
			this.render();

			return Promise.resolve();
		},

		render: function () {
			try {
				window.addEventListener('message', this.onMessage.bind(this));
				this.postMessage({
					name:'glassLoaded'
				});
			} catch (error) {
				console.log(error);
			}

			return Promise.resolve(this);
		}

	});

	return mobileView;

});