class DesktopAppstoreController< ApplicationController

	def appstore
		render "desktop/appstore", :layout => false
	end 

	def widgets
		render "desktop/appstore/widgets", :layout => false
	end

	def onlinestore
		render "desktop/appstore/onlinestore", :layout => false
	end

	def getuserwidgets
		@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
		render :json=>@widgets.to_json
	end

	def widgets_settings
		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
		
		render :json=>@msg.to_json 
	end
	
end