class Admin::DesignsController < OrbitBackendController
  require "net/http"
  require "uri"
  require 'zip/zip'

  before_filter :authenticate_user!
  before_filter :is_admin? 
  before_filter :for_admin_only

  def upload_package
    if !params[:design].nil?
    temp_file = Tempfile.new("temp_file")
    original_file = params[:design][:package_file]
      #if original_file.content_type == 'application/zip'
        temp_file.write(original_file.read.force_encoding('UTF-8'))
        temp_file.rewind
        filename = File.basename(original_file.original_filename,".zip")
        unzip_design(temp_file, filename)
      #else
      #  flash[:error] = "Upload file should be in zip format"
      #end
      temp_file.close
    end
  end

  def index
    @designs = params[:sort] ? get_sorted_and_filtered("designs") : Design.all
  end

  def new
    @design = Design.new
  end

  def update
    @design = Design.find(params[:id])
    @design.update_attributes(params[:design])
    # if @design.update_attributes(params[:design])
    #   flash[:notice] = "Successfully updated design and tasks."
    #   redirect_to admin_designs_url(@design)
    # else
    #   render :action => 'edit'
    # end

    respond_to do |format|
      format.js  {nil}
    end
  end

  def update_file
    @design = Design.find(params[:id])
    case params[:type]
    when 'layout', 'css_default', 'css_reset'
      @object = @design.send(params[:type])
    when 'javascripts', 'themes'#, 'images'
      @object = @design.send(params[:type]).find(params[:object_id])
    end
    Dir.mktmpdir('f_path') { |dir|
      temp_file = File.new(dir + '/' + File.basename(@object.file.url), 'w+') 
      temp_file.write(params[:html_code].force_encoding('UTF-8'))
      @object.remove_file!
      @object.file = temp_file
      @object.save
    }
  end

  def edit_file
    @design = Design.find(params[:id])
    filename = params[:filename]
    files = @design.themes + @design.javascripts + @design.images
    file_to_removed = files.find{ |obj|
      obj.file_identifier == filename
    }
    type = file_to_removed._type
    new_file = ""
    Dir.mktmpdir('design_temp'){ |dir|
      temp_file = File.new(dir+'/'+filename,'w+')
      temp_file.write params[:context]
      replace_target = eval("@design.#{type.downcase.pluralize}")
      new_file = replace_target.build(:file => temp_file,:to_save=>true)
      file_to_removed.destroy
      new_file.save
      temp_file.close
    }
    respond_to do |format|
      format.js  {}
    end
  end

  def edit
    @design = Design.find(params[:id])
  end

  def destroy
    @design = Design.find(params[:id])
    if @site.design == @design
      flash[:error] = "Failed! You can not delete a design that used by default "
    else
      @design.destroy
      flash[:notice] = "Successfully deleted design."
    end
    redirect_to admin_designs_url
  end

  def create
    @design = Design.new(params[:design])
    if @design.save
        redirect_to admin_designs_url
      else
        render :action => 'new'
      end
  end

  def delete
    if params[:ids]
      designs = Design.any_in(:_id => params[:ids]).destroy_all
    end
    redirect_to admin_designs_url(:direction => params[:direction], :sort => params[:sort], :sort_options => params[:sort_options])
  end

  def upload_image
    @design = Design.find(params[:id])
    @image = @design.images.build(params[:image])
    @image.save
    render :layout => false
  end
  
  protected
  
  def unzip_design(file, zip_name)
    Zip::ZipFile.open(file) { |zip_file|
      design = Design.new.from_json(zip_file.read("#{zip_name}/info.json"))
      Dir.mktmpdir('f_path') { |dir|
        themes_entries = []
        javascripts_entries = []
        images_entries = []

        zip_file.entries.each do |entry|
          case (path = entry.to_s)
            when /\A(#{zip_name})\/(default\.css)\z/    #for default css
              design.build_css_default(:file => get_temp_file(zip_file, dir, entry))
            when /\A(#{zip_name})\/(reset\.css)\z/    #for reset css
              design.build_css_reset(:file => get_temp_file(zip_file, dir, entry))
            when /\A(#{zip_name})\/(layout\.html)\z/    #for layout html
              design.build_layout(:file => get_temp_file(zip_file, dir, entry))
            when /\A(#{zip_name})\/(themes)\/.*(\.css)\z/   #for themes css
              themes_entries << entry
            when /\A(#{zip_name})\/(javascripts)\/.*(\.js)\z/   #for js
              javascripts_entries << entry
            when /\A(#{zip_name})\/(images)\/.*((\.jpg)|(\.png)|(\.gif))\z/   #for img
              images_entries << entry
          end
        end

        ['themes', 'javascripts', 'images'].each do |type|
          eval("#{type}_entries").each do |entry|
            eval("design.#{type}").build(:file => get_temp_file(zip_file, dir, entry))
          end
        end
      }
      design.save
    }
  end

  def get_temp_file(zip_file, dir, entry)
    filename = File.basename(entry.to_s)
    temp_file = File.new(dir + '/' + filename, 'w+') 
    temp_file.write (zip_file.read entry ).force_encoding('UTF-8')
    temp_file
  end

end
