class Desktopapp::DesktopAppAppstore < Sinatra::Base
	 register Sinatra::Warden
	get '/desktop_appstore/appstore' do
		erb :appstore
	end

	get '/desktop_appstore/widgets' do
		erb :'appstore/widgets'
	end

	get '/desktop_appstore/getuserwidgets' do
		# @widgets = current_user.desktop.desktop_widgets
		# @groups = Array.new
		# @sections = current_user.desktop.sections

		# @sections.each do |section|
		# 	@groups << section.groups
		# end
		
		# @widgets.each do |widget|
		# 	@count = 0;
		# 	@sectionids = Array.new
		# 	@groups.each do |group|
		# 		group.each do |grp|
		# 			@widge = 0
		# 			@gid = widget.id.to_s
		# 			@widge = grp.tiles.where(:data_content.all => [@gid]).count
		# 			@count = @count + @widge
		# 			if @widge > 0
		# 				@sectionids << grp.section_id
		# 			end
		# 		end
		# 	end
		# 	if @count > 0
		# 		widget.status = "Installed"
		# 		widget.section = @sectionids
		# 	else
		# 		widget.status = "Downloaded"
		# 	end
		# end
		# @widgets.to_json
		current_user.to_json
	end

	get '/desktop_appstore/widgets_settings' do
		what = params["what"]
		@widgetid = params["widget"]
		@sectionid = params["section"]
		@msg = Array.new
		case what
			when "remove"
				@section = Section.find(@sectionid)
				@groups = @section.groups
				@groups.each do |group|
					@tile = group.tiles.where(:data_content.all => [@widgetid])
					if @tile.count > 0
						@thistile = @tile 
					end
				end
				@t = Tile.find(@thistile.first.id)
				@t.delete
				@msg << {"success"=>true}
			when "add"
				@widget = current_user.desktop.desktop_widgets.find(@widgetid)
				@section = Section.find(@sectionid)
				@groups = @section.groups
				@totalwidgets = 0
				@groups.each do |group|
					@tile = group.tiles.where(:data_content.all => [@widgetid]).count
					if @tile > 0
						@msg << {"success"=>false,"error"=>"Duplicate widget"}
					else
						no_of_widgets = group.tiles.where(:data_category.all => ["widget"]).count
						@totalwidgets = @totalwidgets + no_of_widgets
					end
				end
				if @totalwidgets >= 12
					@msg << {"success"=>false,"error"=>"Section full"}
				else
					wshape = @widget.shape
					wdata_content = @widgetid
					wdata_category = "widget"
					wname = @widget.name
					if @groups.first.tiles.where(:data_category.all => ["widget"]).count >= 6
						groupid = @groups.last.id
					else
						groupid = @groups.first.id
					end
					Tile.create(data_category: wdata_category,data_content: wdata_content, group_id: groupid, position: 10, title: wname, shape: wshape)
					@msg << {"success"=>true}
				end
		end
		@msg.to_json 
	end

end