class DesktopController< ApplicationController
  layout 'desktop'
  before_filter :authenticate_user!
  before_filter :check_desktop_open, :only => [:index,:show]

  #to load pages...

  # caches_page :index

  def index
    @desktop = current_user.desktop
    if(@desktop.theme.nil?)
      @desktop.theme = DesktopTheme.first.id.to_s
      @desktop.wallpaper = nil
      @desktop.save!
    end
    @currentusername = current_user.name
    @currentname = current_user.first_name + current_user.last_name rescue ""
    @title = "Desktop - " + @currentusername
    @section = @desktop.sections.first
  end

  def compatibility
    render :layout => "compatibility" 
  end
  
  def desktop_container
    render :layout => false
  end
  
  def app_manager
     render :layout => false
  end
  
  def allsections
    render :layout => false
  end
  
  def settings
    render :layout => false
  end
  
  def get_themes
    desktop = current_user.desktop
    @themes = DesktopTheme.all
    @wallpapers = desktop.desktop_wallpapers.all
    render "desktop/settings/themes", :layout => false
  end
  
  def sections
    render "desktop/settings/sections", :layout => false
  end
  
  def connections
    # @url = "http://fb.tp.rulingcom.com/login?callback=http://harry.tp.rulingcom.com/facebook/register_fb?user="+current_user.id.to_s
    @user_id = current_user.id.to_s
    render "desktop/settings/connections", :layout => false
  end

  def wallpaper_upload
    desktop = current_user.desktop
    wallpaper = desktop.desktop_wallpapers.new
    
    if params[:imagelink] != ""
      wallpaper.type = "url"
      wallpaper.link = params[:imagelink]
      wallpaper.save!
    elsif params[:imagefile]
      wallpaper.file = params[:imagefile]
      wallpaper.type = "file"
      wallpaper.save!
    end

    render :json=>{"success"=>true}.to_json
  end
  
 
  #ajax data load....
  
  def save_desktop_settings
    @desktop = Desktop.find(params["desktopid"])
    @savewhat = params["save"]
    case @savewhat
    when "theme"
      @desktop.update_attributes(:theme => params["theme"])
      @desktop.update_attributes(:wallpaper => nil)
    when "desktopnames"
      @sections = @desktop.sections
      x = 0;
      @sections.each do |section|
        @desktopnewnames = params["desktopnms"]
        section.update_attributes(:name => @desktopnewnames[x] )
        x = x+1
      end
    when "appnewsection"
      @section = Section.find(params["newsectionid"])
      @groups = @section.groups
      @app = Tile.find(params["appid"])
      @groups.each do |group|
        @tiles = group.tiles.where(:data_category.all => ["app"])
        if @tiles.length < 12
          @app.update_attributes(:group_id => group.id)
          break
        end
      end
      when "customtheme"
        @desktop.update_attributes(:theme => "custom")
        @desktop.update_attributes(:customtheme => params['theme'])
      when "wallpaper"
        @desktop.update_attributes(:wallpaper => params["wallpapernm"])
      end
     a = Array.new
     a << {"success"=>"true"}
     render :json=>a.to_json
  end
  
  def get_desktop_settings
     @desktop = Desktop.find(params["desktopid"])
     @getwhat = params["get"]
     case @getwhat
      when "desktop"
        render :json => @desktop.to_json
      when "sectionnames"
        secnames = Array.new
        @sections = @desktop.sections
        @sections.each do |section|
          secnames << section.name
        end
        render :json => secnames.to_json
      when "theme"
        @theme = @desktop.theme
        render :json => @theme.to_json
     end
  end
  
  def getgroups
    @section = Section.find(params["sectionid"])
    @groups = @section.groups
    gr = Array.new
    @groups.each do |group|
      a = Array.new
      @t = group.tiles

      @t.each do |tile|
        data_content = ""
        jsfile = []
        cssfile = ""
        shape = "w1 h1"
        link = ""
        icon= ""
        fullsize = false
        if tile.data_category == "widget"
          widge = DesktopWidget.find(tile.desktop_widget_id.to_s)
          # data_content = widge.widget_layout.file
          data_content = "/desktop/widget_layout?id="+tile.desktop_widget_id.to_s
          jsfile = widge.javascripts.collect{|js| js.file.as_json[:file]}
          cssfile = widge.css_default.file.as_json[:file]
          shape = widge.shape
          title = widge.name
          icon = widge.images.where(:name => widge.icon).first.file.url
          # binding.pry
          fullsize = widge.fullsize
        else
          app = DesktopApp.find(tile.desktop_app_id.to_s)
          title = app.name
          link = app.url
          icon = app.images.where(:name => app.icon).first.file.url

        end
          gr << {"id"=>tile.id,"data_category"=>tile.data_category,"data_content"=>data_content,"js"=>jsfile,"css"=>cssfile,"shape"=>shape,"position"=>tile.position,"row"=>tile.row,"column"=>tile.column, "title"=>title,"fullsize"=>fullsize,"link"=>link,"icon"=>icon}
       
        
      end
      # gr << a
    end
    render :json =>gr.to_json
  end

  def widget_layout
    widget = DesktopWidget.find(params[:id])
     # link = '<link href="'+widget.css_default.file.to_s+'" media="screen" rel="stylesheet" type="text/css" />'
    css = widget.css_default.content;
    css = "<style>" + css + "</style>"
    content = widget.widget_layout.body
    dhtml = css + content
    render :text => dhtml.html_safe
  end
  
  def getsectionlist
    @desktop = Desktop.find(params["desktopid"])
    @sections = @desktop.sections
    render :json => @sections.to_json 
  end
  
  def temp_func
     @section = Section.find(params["sectionid"])
      @groups = @section.groups
      
      @groups.each do |group|
        a = 1;
        @tiles = group.tiles
        @tiles.each do |tile|
          tile.update_attributes({:data_category => "widget",:data_content => "temp", :position => a})
          a = a+1;
        end
      end
      b = Array.new
       b << {"success"=>"true"}
       render :json=>b.to_json
  end
  
  def getapplist
     @desktop = Desktop.find(params["desktopid"])
     @sections = @desktop.sections
     a = Array.new
     @sections.each do |section|
       @groups = section.groups
       @groups.each do |group|
         @tiles = group.tiles.where(:data_category.all => ["app"])
         a << @tiles
       end
     end
     render :json=>a.to_json
  end

   def getapplistforManager
    @dwss = DesktopWidget.all
    @dapps = DesktopApp.all
    @tiles = Array.new
    desktop = Desktop.find(params['desktopid'])
    sections = desktop.sections
    sections.each do |section|
      groups = section.groups
      groups.each do |group|
        @tiles += group.tiles
      end
    end
    @validtiles = Array.new
    @allWidgets = Array.new
    @dwss.each do |dw|
      @id = dw.id
      @validtiles = @tiles.select{|t| t.desktop_widget_id == @id}
      @sections = Array.new
      @validtiles.each do |vt|
        grp = Group.find(vt.group_id)
        sec = Section.find(grp.section_id);
        @sections << {"id"=>sec.id,"name"=>sec.name}
      end
      @allWidgets << {"id"=>dw.id, "data_category"=> "widget","title" => dw.name, "version" => dw.version, "author"=>dw.author, "last_update"=>dw.updated_at, "icon"=>dw.images.where(:name=>dw.icon).first.file.url, "text_color" => dw.text_color, "background" => dw.bg_color, "sections" => @sections}
    end
    validtiles = Array.new
    @dapps.each do |da|
      @id = da.id
      @validtiles = @tiles.select{|t| t.desktop_app_id == @id}
      @sections = Array.new
      @validtiles.each do |vt|
        grp = Group.find(vt.group_id)
        sec = Section.find(grp.section_id);
        @sections << {"id"=>sec.id,"name"=>sec.name}
      end
      @allWidgets << {"id"=>da.id, "data_category"=> "app","title" => da.name, "version" => da.version, "author"=>da.author, "last_update"=>da.updated_at, "icon"=>da.images.where(:name=>da.icon).first.file.url, "sections" => @sections}
    end
    render :json=>@allWidgets.to_json
  end
  
  def newpositions
    @newpositions = params[:newpositions]

    @newpositions.each do |t|
      @this_tile = t.last
      @tile = Tile.find(@this_tile['id'])
      @tile.update_attributes({:row => @this_tile['row'],:column => @this_tile['col']})
    end
    # @newpositions = params["newpos"]
    # @section = Section.find(params["sectionid"])
    # @groupids = params["groupids"]
    # @groups = @section.groups
    #  z = 0
    # @newpositions.each do |grp|
    #   x = 1
    #   grp.each do |tileid|
    #     if x != 1
    #       y = 1
    #       tileid.each do |id|
    #         @tile = Tile.find(id)
    #         @tile.update_attributes({:position => y})
    #         if @tile.group_id != @groupids[z]
    #           @tile.update_attributes({:group_id => @groupids[z]})
    #         end
    #          y = y + 1
    #       end
    #       z = z + 1
    #     end
    #     x = x + 1
    #   end
    # end
    b = Array.new
    b << {"success"=>"true"}
    render :json=>b.to_json
  end
  
  def forgmail
   
    feed = Net::HTTP.get_response(URI.parse("https://mail.google.com/mail/feed/atom")).body
    render :xml=>feed
  end

  def appactivation
    @group = Section.find(params[:section_id]).groups.first
    @type = params[:type]
    if @type == "widget"
      @widget = DesktopWidget.find(params[:id])
      status = params[:status]

      case status
      when "true"
        tile = Tile.new(data_category: "widget", position: 8, desktop_widget_id: @widget.id)
        @group.tiles+=[tile]
        @group.save
      when "false"
        tile = @group.tiles.where("desktop_widget_id"=>@widget.id).first
        if tile != nil
          tile.destroy
        end
      end
    end

    if @type == "app"
      @app = DesktopApp.find(params[:id])
      status = params[:status]
      case status
      when "true"
        tile = Tile.new(data_category: "app", position: 8, desktop_app_id: @app.id)
        @group.tiles+=[tile]
        @group.save
      when "false"
        tile = @group.tiles.where("desktop_app_id"=>@app.id).first
        if tile != nil
          tile.destroy
        end
      end
    end

    b = Array.new
    b = {"success"=>"true"}
    render :json=>b.to_json
  end
 
  protected

  def check_desktop_open
    @site = Site.first
    if !@site.desktop_closed  #Need to be change
      redirect_to '/admin/dashboards'  
    end
  end

  
end
