class Admin::SitePanelController < OrbitAdminController
  
  def initialize
    super
    @app_title = "client_management"
  end

  def index
    @site_construct = SiteConstruct.new
    @module_app = ModuleApp.where(:title=>@app_title).first
  end
  def server_manager
    @module_app = ModuleApp.where(:title=>@app_title).first
    @categories = @module_app.categories
    @tags = []
    @filter_fields = filter_fields(@categories,@tags)
    @site_servers = SiteServer.all.with_categories(filters("category")).with_status(filters("status"))
    @site_servers = search_data(@site_servers,[:server_name,:ip]).page(params[:page].to_i).per(10)
    if request.xhr?
      render :partial => "server_manager_index"
    end
  end
  def edit_server_info
    @module_app = ModuleApp.where(:title=>@app_title).first
    if params[:type] == 'update'
      @site_server = SiteServer.find(params[:id]) rescue nil
      if @site_server.present?
        @site_server.update_attributes(site_server_params)
      else
        @site_server = SiteServer.create(site_server_params)
      end
      redirect_to admin_site_panel_server_manager_path
    elsif params[:type] == 'create'
      @site_server = SiteServer.new
    elsif params[:type] == 'delete'
      SiteServer.find(params[:id]).destroy
      redirect_to admin_site_panel_server_manager_path
    elsif params[:type] == 'detect_sites'
      Thread.new do
        system("bundle exec rake create_site:detect_sites")
      end
      render :json => {"success"=>true}
    elsif params[:type] == 'see_infos'
      if params["key"].blank?
        thread = Multithread.where(:key=>'detect_sites').first
        if thread.nil?
          thread = Multithread.where(:key=>'execing_commands').first
        else
          if thread.status["status"] == "finish" || thread.status["status"] == "error"
            exec_thread = Multithread.where(:key=>'execing_commands').first
            thread = exec_thread if !exec_thread.nil?
          end
        end
      else
        thread = Multithread.where(:key=>params["key"]).first
      end
      if thread.nil?
        render :json => {"infos"=>[],"status"=>"starting"}
      else
        render :json => thread.status
      end
    elsif params[:type] == 'get_server_names'
      render :json => (SiteServer.all.map{|s| s.server_name rescue ""}.select{|n| !n.blank?} rescue [])
    else
      @site_server = SiteServer.find(params[:id])
    end
  end
  def create
    site_construct = SiteConstruct.new(site_construct_params)
    site_construct.user_id = current_user.id.to_s
    site_construct.status = "creating"
    site_construct.save
    git_url = "http://ruling.digital/git"#"http://gitlab.tp.rulingcom.com/orbit_chiu1/orbit4-5.git"
    git_template_url = "http://gitlab.tp.rulingcom.com/themes/default-theme.git"
    git_extension_url = "http://gitlab.tp.rulingcom.com/core/default-modules.git"
    site_server = SiteServer.where(:server_name=>site_construct.server_type).first
    ip = site_server.ip
    user = site_server.account
    password = site_server.password
    site_name = site_construct.site_name
    domain_name = site_construct.domain_name
    port = site_construct.port
    db_name = site_construct.db_name
    path = site_construct.path
    site_construct_id = site_construct.id.to_s
    if params[:site_construct][:copy_id].blank?
      Thread.new do
        system("bundle exec rake create_site:create_site['#{git_template_url}','#{git_extension_url}','#{git_url}','#{ip}','#{user}','#{password}','#{site_name}','#{domain_name}','#{port}','#{db_name}','#{path}','#{site_construct_id}']")
      end
    else
      Thread.new do
        system("bundle exec rake create_site:copy_site['#{ip}','#{user}','#{password}','#{site_name}','#{domain_name}','#{port}','#{db_name}','#{path}','#{site_construct_id}','#{params[:site_construct][:copy_id]}']")
      end
    end
    redirect_to "#{admin_site_panel_sites_list_path}?id=#{site_construct_id}"
  end
  def create_site
    site_construct = SiteConstruct.find(params[:id])
    site_construct.user_id = current_user.id.to_s
    git_url = "http://ruling.digital/git"#"http://gitlab.tp.rulingcom.com/orbit_chiu1/orbit4-5.git"
    git_template_url = "http://gitlab.tp.rulingcom.com/themes/default-theme.git"
    git_extension_url = "http://gitlab.tp.rulingcom.com/core/default-modules.git"
    site_server = SiteServer.where(:server_name=>site_construct.server_type).first
    ip = site_server.ip
    user = site_server.account
    password = site_server.password
    site_name = site_construct.site_name
    domain_name = site_construct.domain_name
    port = site_construct.port
    db_name = site_construct.db_name
    path = site_construct.path
    site_construct_id = params[:id]
    Thread.new do
      system("bundle exec rake create_site:create_site['#{git_template_url}','#{git_extension_url}','#{git_url}','#{ip}','#{user}','#{password}','#{site_name}','#{domain_name}','#{port}','#{db_name}','#{path}','#{site_construct_id}']")
    end
    render :json =>{"success"=>true}
  end
  def edit_site
    if params[:type] == 'delete'
      Thread.new do
        system("bundle exec rake create_site:delete_site[#{params[:id]}]")
      end
    elsif params[:type] == 'close'
      Thread.new do
        system("bundle exec rake exec_commands:exec_commands[#{params[:id]},,close_site]")
      end
    elsif params[:type] == 'open'
      Thread.new do
        system("bundle exec rake exec_commands:exec_commands[#{params[:id]},,open_site]")
      end
    elsif params[:type] == 'detail'
      @site = SiteConstruct.find(params[:id])
      render 'see_detail_for_created_site' and return
    elsif params[:type] == 'change_server_name'
      cmd = "bundle exec rake create_site:change_site_server_name[#{params[:id]},'#{params[:site_construct][:domain_name]}']"
      system(cmd)
      redirect_to :back and return
    elsif params[:type] == 'delete_from_list'
      SiteConstruct.find(params[:id]).destroy
      redirect_to :back and return
    else
      Thread.new do
        if params[:id].blank? && !params[:server_names].blank?
          system("bundle exec rake exec_commands:exec_commands[,'#{params[:commands]}',exec_all,'#{params[:server_names].join('////')}']")
        else
          system("bundle exec rake exec_commands:exec_commands[#{params[:id]},'#{params[:commands]}',exec_commands]")
        end
      end
    end
    render :json =>{"success"=>true}
  end
  def sites_list
    @module_app = ModuleApp.where(:title=>@app_title).first
    @categories = @module_app.categories
    @sites = SiteConstruct.any_in(:hidden=>[false,nil]).desc(:id)
    @site_servers = SiteServer.all.with_categories(filters("category"))
    @sites = (params[:server_name].blank? ? @sites : @sites.where(:server_type=>params[:server_name]))
    @sites = @sites.any_in(:server_type => @site_servers.map{|s| s.server_name})
    @sites = search_data(@sites,[:domain_name,:site_name,:school_name,:status]).page(params[:page].to_i).per(10)
    if request.xhr?
      render :partial => "sites_list_table"
    end
  end
  def site_infos
    site_construct = SiteConstruct.where(:id=>params[:id]).first
    if site_construct.nil?
      render :json => {:status=>"creating",:infos=>[]}
    else
      render :json => {:status=>site_construct.status,:infos=>site_construct.infos}
    end
  end
  private

  def site_construct_params
    site_construct_params = params.require(:site_construct).permit!
    site_construct_params = site_construct_params.except(:copy_id)
    return site_construct_params
  end
  def site_server_params
    params.require(:site_server).permit!
  end
end