class Admin::ModuleStoreController < OrbitBackendController

  def index
    if get_site.site_token?
      if get_site.store_confirmation
        @extensions = get_extensions
        @store_confirmation = true
      else
        @extensions = []
        @store_confirmation = false
      end
      @downloaded_extensions = get_downloaded_extension
    else
      @store_confirmation = true
       @extensions = []
      @downloaded_extensions = get_downloaded_extension
    end
  end

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

  def download
    #get extension related values
    extension = get_extension(params[:id]) rescue nil
    extension_name = extension["key"].to_s
    git_repository_url = extension["git_url"]
    tag = extension["tag"]
    module_installed = File.read("downloaded_extensions.rb").include?(extension["key"])

    if module_installed.eql?(false)
      @download_link = "gem '#{extension_name}', :git => '#{git_repository_url}', :tag => '#{tag}'"
      File.open("downloaded_extensions.rb", 'a') do |file|
        file.puts @download_link
      end
    end
    Bundler.with_clean_env { `cd #{Rails.root} && bundle install && touch tmp/restart.txt` }
    redirect_to admin_module_store_path
  end

  def toggle_module
    temp_extensions=File.open("#{Rails.root}/extensions.tmp.rb", 'w')
    extensions = File.new("#{Rails.root}/downloaded_extensions.rb", "r")

    while (extension = extensions.gets)
      if params[:module].any? { |mod|  extension.include?("gem '"+mod+"'")}
        @mod = ModuleApp.where(:key=>extension.split("'")[1]).first
        if extension.start_with?("# ")
          temp_extensions << extension.gsub("# ","")
          toggle_item(@mod , true)
        else
          temp_extensions << "# "+extension
          toggle_item(@mod , false)
        end
      else
        temp_extensions << extension
      end
    end

    extensions.close
    temp_extensions.close

    FileUtils.mv("#{Rails.root}/extensions.tmp.rb","#{Rails.root}/downloaded_extensions.rb")
    Bundler.with_clean_env { `cd #{Rails.root} && bundle install && touch tmp/restart.txt` }
    render :text => "true"
  end

  def remove_module
    temp_extensions=File.open("#{Rails.root}/extensions.tmp.rb", 'w')
    extensions = File.new("#{Rails.root}/downloaded_extensions.rb", "r")

    while (extension = extensions.gets)
      if extension.include?("gem '"+params[:module]+"'")
        @mod = ModuleApp.where(:key=>extension.split("'")[1]).first
        toggle_item(@mod , false)
        temp_extensions << ""
      else
        temp_extensions << extension
      end
    end

    extensions.close
    temp_extensions.close

    FileUtils.mv("#{Rails.root}/extensions.tmp.rb","#{Rails.root}/downloaded_extensions.rb")
    Bundler.with_clean_env { `cd #{Rails.root} && bundle install && touch tmp/restart.txt` }
    render :text => "true"
  end

  def restart_server
    render :text => "true"
  end

  protected

  def get_extensions
    extensions = store_session.extensions

    exist_exts = []
    ext_file = File.new("#{Rails.root}/downloaded_extensions.rb", "r")

    while (exist_ext = ext_file.gets)
      status = !exist_ext.start_with?("# ")
      exist_ext = exist_ext.split(',')

      if !extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}.blank?
        extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}[0]['installed']=true
        extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}[0]['enabled']=status
        extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}[0]['installed_version']=exist_ext[2].split(/[\'\"]/)[1]
        if extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}[0]['tag'] != exist_ext[2].split(/[\'\"]/)[1]
          extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}[0]['updated'] = false
        else
          extensions.select{|ext| ext['key']==exist_ext[0].split(/[\'\"]/)[1]}[0]['updated'] = true
        end
      end
    end

    ext_file.close

    extensions
  end

  def get_extension(id)
    store_session.get_extension(id)
  end

  def get_downloaded_extension
    downloaded_extensions = []
    
    extensions = File.new("#{Rails.root}/downloaded_extensions.rb", "r")
    
    while (extension = extensions.gets)
      status = !extension.start_with?("# ")
      extension = extension.split(',')

      downloaded_extensions << {'name' => extension[0].split(/[\'\"]/)[1], 'repo' => extension[1].split(/[\'\"]/)[1], 'tag' => extension[2].split(/[\'\"]/)[1], 'status' => status}
    end

    extensions.close

    downloaded_extensions.to_json
  end 

  def toggle_item(module_key, active)
    if !module_key.nil?
      Item.where(:module_app_id=>module_key._id).each  do |item|
        item.is_published = active
        item.menu_enabled_for = {"zh_tw" => active.to_s, "en" => active.to_s}
        item.save
      end
    end
  end

  private

  def get_site
    @site ||= Site.first
  end

end