# encoding: utf-8
require 'fileutils'
class Filefield

  include Mongoid::Document
  include Mongoid::Timestamps


  field :title, :type=> String ,default:"patchfile"
  field :file_show, :type=> Hash ,default:{"ckeditor"=>0,"site-preference(two-site-logo)"=>0,"member"=>0}
  after_update :updatefile


  def enabled_for?(lang)
  	if lang.nil?
  		return true
  	else
  		return self.choose_lang.include?(lang)
  	end
  end
  def lastpath dir_path
	dir_path = dir_path.gsub('\\','/')
	dir_arr= dir_path.split('/')
	dir_str=''
	dir_arr.delete_at(-1)
	dir_arr.each_with_index do |path,index|
		dir_str = dir_str + path 
		if index != dir_arr.count - 1
			dir_str = dir_str +"/"
		end
	end
	return dir_str
  end
  def updatefile
	self.file_show.each do |key,value|
		if value == 1
			@model_path = ENV['PWD'] + '/app/models/'
			@helper_path = ENV['PWD'] + '/app/helpers/'
			@views_path = ENV['PWD'] + '/app/views/'
			@controller_path = ENV['PWD'] + '/app/controllers/'
			if key == "ckeditor"
				app_path = File.expand_path(__dir__)
				app_path = lastpath(app_path)
				app_path = lastpath(app_path)
				@ckeditor_path = ENV['PWD'] + '/app/assets/javascripts/ckeditor/'
				puts 'copying CKEDITOR'
				@aa = FileUtils.cd(app_path+'/updatefiles/')
				puts @aa.to_s
				begin
					FileUtils.cp('config.js.erb' , @ckeditor_path)
					puts @ckeditor_path
				rescue 
					puts 'error copy'
				end
			elsif key == "site-preference(two-site-logo)"
				app_path = File.expand_path(__dir__)
				app_path = lastpath(app_path)
				app_path = lastpath(app_path)
				puts app_path
				puts 'copying site'
				FileUtils.cd(app_path+'/updatefiles/')
				begin
					FileUtils.cp('site.rb' , @model_path)
					FileUtils.cp('application_helper.rb' , @helper_path)
					FileUtils.cd('admin/')
					FileUtils.cp('preference.html.erb',@views_path+'/admin/sites/')
				rescue 
					puts 'error copy'
				end
			elsif key == "member"
				app_path = File.expand_path(__dir__)
				app_path = lastpath(app_path)
				app_path = lastpath(app_path)
				FileUtils.cd(app_path+'/updatefiles/')
				puts 'copying member'
				begin
					FileUtils.cp('member_profile.rb' , @model_path)
					FileUtils.cd('admin')
					FileUtils.cp('members_controller.rb' , @controller_path+'/admin/')
				rescue 
					puts 'error copy'
				end
			end
			FileUtils.cd(Rails.root.to_s)
		end
	end
  end

end
