class Admin::ModuleStoreController < OrbitBackendController
    
  @@store = STORE_CONFIG[:store_settings]["url"]

  def index
  	@extensions = get_extensions
  end

  def show
  	@extension = get_extension(params[:id]) rescue nil
  end

  def download
    #get extension related values
  	extension = get_extension(params[:id]) rescue nil
  	download_link = @@store + "/"+ extension["extension"]["extension"]["url"]
  	downloaded_file_name = extension["extension_filename"]
    module_app_name = downloaded_file_name.split(/(.zip)/).first

    #check if the directory exists or not
    @module_status = Dir.exists?("#{Rails.root}/vendor/built_in_modules/#{module_app_name}")
    if @module_status.eql?(true)
      flash[:notice] = "This module is already installed"
    else
     download_extension(download_link, downloaded_file_name,module_app_name)
     flash[:notice] = "This module has been successfully installed"
    end
  	redirect_to admin_module_store_path
  end

  protected

  def get_extensions
  	JSON.parse(open("#{@@store}/api/extensions").read)
  end

  def get_extension(id)
  	JSON.parse(open("#{@@store}/api/extensions/#{id}").read)
  end

  def download_extension(download_link, downloaded_file_name,module_app_name)
  	puts %x(wget "#{download_link}")
  	puts %x(unzip "#{downloaded_file_name}")
    puts %x(mv #{module_app_name} "#{Rails.root}/vendor/built_in_modules/")
    puts %x(rm "#{downloaded_file_name}")
  	site_restart
  end
end