class Admin::SitesController < OrbitBackendController
  
  before_filter :authenticate_user!
  before_filter :is_admin?
  before_filter :get_site
  before_filter :git_branch, only: [:update_manager, :get_update_history, :check_updates, :update_orbit]
  before_filter :git_tags, only: [:update_manager, :get_update_history, :check_updates, :update_orbit]
  
  # def index
  #   @site = Site.first
  #   # redirect_to :action => :new unless @site
  # end
  
  # def new
  #   @site = Site.new
  # end

  def show_system_preference
    @git_commit_list_file = File.new(OrbitSystemPreference::GitCommitListPath, "r") rescue nil
    @db_backup_list_file = File.new(OrbitSystemPreference::ArchiveDbListPath, "r") rescue nil
    @resque_logs_file = File.new(OrbitSystemPreference::ResqueLogFile, "r") rescue nil
    @site = Site.first
  end

  def update
    if params[:site][:default_bar_color] 
      params[:site][:mobile_bar_color] = []
    end
    # if params[:site][:enable_language_detection]
    #   Site.update_all({:default_locale => nil})
    # end

    if params[:site][:phone_number].nil?
      params[:site][:phone_number] = []
    else
      params[:site][:phone_number] = params[:site][:phone_number].values
    end

    @site.update_attributes(params[:site])

    if params[:site][:enable_language_detection].eql?("0")
      Site.update_all({:enable_language_detection => false})
    elsif params[:site][:enable_language_detection].eql?("1")
      Site.update_all({:default_locale => nil})
    end
    
    redirect_to :back
  end

  def mail_setting
    
  end

  def site_info
    
  end

  def sitemap
    @items = get_homepage.children rescue []
  end

  def sitemap_toggle
    @item = Item.find(params[:id])
    @item.sitemap_enabled[params[:temp_locale]] = (!@item.show_in_sitemap_for(params[:temp_locale])).to_s
    @item.save
    if params[:parent]
      @item.children.each do |child|    
        child.sitemap_enabled[params[:temp_locale]] = @item.sitemap_enabled[params[:temp_locale]].to_s
        child.save
      end
    end
    render :nothing => true
  end

  def system_info
    @disk_free = `df -h /`.gsub("\n","<br/>").html_safe
    @nginx_version = %x[/opt/nginx/sbin/nginx -v 2>&1].gsub("\n","<br/>              ").html_safe
    @mongo_version = `mongod --version`.split("\n")[0].html_safe
    @linux_version = `lsb_release -d`.split(":")[1].html_safe

    @user_actions = UserAction.all.desc(:created_at).page(params[:page]).per(100)

    @mail_crons = MailCron.desc(:created_at)

    @mail_cron_logs = MailCronLog.desc(:created_at).page(params[:page]).per(100)

    respond_to do |format|
      format.html # index.html.erb
      format.js
    end

  end

  def search_engine
    
  end

  def preference
      
  end

  def responsive_setting
    @module = ModuleApp.where(:key => "announcement").first
    if @site.phone_number.class.to_s == "BSON::OrderedHash"
      @site.phone_number = []
    end
  end


  def ui_theme
    
  end

  # def reset_default_locale
  #   @site.defalut_locale = params[:default_locale]
  #   if @site.save
  #     render :nothing => true
  #   end
  # end

  def change_design
    design = Design.find(params[:site_id]) rescue nil
    update_design(design) if design
    render :nothing => true
  end

  def update_manager
  end

  def get_update_history
    @update_log = %x{git log --pretty=format:"%ad','%s" --date=short}.split("\n").map{|log| log.gsub("'","").split(",")}.to_json
    render :json => @update_log
  end

  def check_updates
    if (@current_tag.eql?(@latest_tag) == false)
      %x(git fetch origin)
    end
    @new_updates = %x(git log "#{@current_tag}"..."#{@latest_tag}"  --pretty=format:"%ad','%s" --date=short).split("\n").map{|log| log.gsub("'","").split(",")}.to_json
    render :json => @new_updates
  end

  def update_orbit
    result = ""
    need_stash = %x(git diff).blank?
    %x(git stash) unless need_stash
    %x(git fetch origin)
    pull_result = %x(git pull -r --ff-only 2>&1 origin #{@latest_tag})
    %x(git stash pop) unless need_stash

    if pull_result.include? "fatal: Not possible to fast-forward, aborting."
      result = "failed"
    else
      result = "success"
      Bundler.with_clean_env { `cd #{Rails.root} && bundle install && touch tmp/restart.txt` }
    end

    render :text => result
  end

  def restart_server
    render :text => "success"
  end

  def register_site
    @site.register_site
    redirect_to admin_module_store_path
  end

  protected

  def update_design(design)
    @site.design = design
    if @site.save
      theme_id = design.themes.first.id
      Page.all.each do |page|
        page.update_attributes({design_id: design.id, theme_id: (theme_id unless page.root?)})
      end
    end
  end

  private

  def get_site
    @site ||= Site.first
  end

  def git_branch
    @branch = %x(git rev-parse --abbrev-ref HEAD).gsub("\n","")
  end

  def git_tags
    @current_tag = %x(git describe --tags).gsub("\n","")
    @latest_tag = `git ls-remote --tags origin | awk '{print $2}'`.split(/\n/).last.gsub("refs/tags/","") rescue nil
  end
  
end
