class Patchfilefield
  include Mongoid::Document
  include Mongoid::Timestamps
  include OrbitModel::Status
  include OrbitModel::Impression
  # encoding: utf-8
  include OrbitTag::Taggable
  include OrbitCategory::Categorizable
  field :font_array , :type => Hash, default:{}
  field :new_add_font, type: String, default:""
  field :delete_font, type: String, default:""
  field :used_font , :type => Array, default:[]
  field :un_used_font , :type => Array, default:[]
  field :title ,type:String ,default:""
  field :subtitle, localize: true
  field :text, localize: true
#  before_destroy :destroy_email
  scope :can_display, ->{where(:is_hidden=>false,:is_preview => false).any_of({:postdate.lt=>Time.now, :deadline.gt=>Time.now},{:postdate.lt=>Time.now, :deadline=>nil}).order_by([:is_top, :desc],[:postdate, :desc])}
  scope :is_approved, ->{where(:approved => true)}
  before_create :delete_empty_font ,:get_font_to_store,:set_un_used_font , :set_used_font
  before_update :delete_empty_font ,:get_font_to_store,:set_un_used_font , :set_used_font
  before_save :delete_empty_font ,:get_font_to_store,:set_un_used_font , :set_used_font
  after_update :set_config
  after_save :set_config
  #before_create :set_expire
  def delete_empty_font
	self.font_array.each do |font,istrue|
		if font.strip == ""
			self.font_array.delete(font)
		end
	end
  end
  def get_font_to_store
	@ckeditor_path = ENV['PWD'] + '/app/assets/javascripts/ckeditor'
	@filedata = File.read(@ckeditor_path+"/config.js.erb") rescue return
	@name_to_search ="config.font_names"
	@index_of_font = @filedata.index(@name_to_search)
	@font_str = ""
	@end_character
	if @index_of_font != nil
		@inex_start_to_search = @index_of_font + @name_to_search.length
		@str_start = @inex_start_to_search
		if (@filedata[@inex_start_to_search] != "\'" && @filedata[@inex_start_to_search] != "\"")
			for @str_start in @inex_start_to_search..@filedata.length
				break if (@filedata[@str_start] == "\'" || @filedata[@str_start] == "\"")
			end
		end
		@end_character = @filedata[@str_start]
		@str_end = @str_start+1
		if @str_start+1 < @filedata.length
			@str_end = @str_start+1
			for @str_end in @str_start+1..@filedata.length
				break if @filedata[@str_end] == @end_character || @str_end == @str_start
				if @filedata[@str_end] == "="
					@str_end = @str_start
					break
				end
			end
			if @str_end != @str_start
				@font_str = @filedata[@str_start+1...@str_end]
			else
				@font_str = ""
			end
		end
		@font_array = @font_str.split("\;")
		@font_array.map!{|i| i.strip}
		@font_array.delete("")
		@font_array.each do |font|
			@i = 0
			if font != self.delete_font
				self.font_array.keys.each do |each_font|
					if each_font == font
						@i = 1
					end
					break if @i == 1
				end
				if @i == 0
					self.font_array = self.font_array.merge({font => true})
				end
			end
		end
	end
	if self.new_add_font.strip !=""
		@i = 0
		self.font_array.keys.each do |each_font|
			if each_font == self.new_add_font
				@i = 1
			end
			break if @i == 1
		end
		if @i == 0
			self.font_array = self.font_array.merge({self.new_add_font.strip => true})
		end
		self.new_add_font = ""
	end
  end
 # def set_expire
   # self.expirable_created_at = Time.now if self.is_preview
  #  return true
 # end
  def set_un_used_font
	@un_use_font = []
	self.font_array.each do |font,istrue|
		if istrue == false
			@un_use_font.push font.strip
		end
	end
	self.un_used_font = @un_use_font
  end
  def set_used_font
	@use_font = []
	self.font_array.each do |font,istrue|
		if istrue == true
			@use_font.push font.strip
		end
	end
	@use_font.delete("")
	self.used_font = @use_font
  end
  def check_font_state
	@ckeditor_path = ENV['PWD'] + '/app/assets/javascripts/ckeditor'
	@filedata = File.read(@ckeditor_path+"/config.js.erb") rescue return
	@name_to_search ="config.font_names"
	@index_of_font = @filedata.index(@name_to_search)
	@font_str = ""
	@end_character
	@str_start
	@str_end
	@font_array
	if @index_of_font != nil
		@inex_start_to_search = @index_of_font + @name_to_search.length
		@str_start = @inex_start_to_search
		if (@filedata[@inex_start_to_search] != "\'" && @filedata[@inex_start_to_search] != "\"")
			for @str_start in @inex_start_to_search..@filedata.length
				break if (@filedata[@str_start] == "\'" || @filedata[@str_start] == "\"")
			end
		end
		@end_character = @filedata[@str_start]
		@str_end = @str_start+1
		if @str_start+1 < @filedata.length
			@str_end = @str_start+1
			for @str_end in @str_start+1..@filedata.length
				break if @filedata[@str_end] == @end_character || @str_end == @str_start
				if @filedata[@str_end] == "="
					@str_end = @str_start
					break
				end
			end
			if @str_end != @str_start
				@font_str = @filedata[@str_start+1...@str_end]
			else
				@font_str = ""
			end
		end
		@font_array = @font_str.split("\;")
		@font_array.map!{|i| i.strip}
		@font_array.delete("")
		if !check_eql_array(@font_array,self.used_font)
			return false
		else
			return true
		end
	end
  end
  def set_config
	@istrue = check_font_state
	if @istrue == false
		@delete_font_array = []
		self.un_used_font.each do |font_to_delete|
			if  @font_array.include? font_to_delete.strip
				@delete_font_array.push font_to_delete.strip
			end
		end
		@delete_font_array.push(self.delete_font) if self.delete_font != ""
		self.delete_font = ""
		puts "111111111111111111111111111111111111111111111111"
		puts @delete_font_array
		@add_font_array = []
		@use_font = self.used_font rescue []
		@use_font.each do |font_to_add|
			if  !(@font_array.include? font_to_add.strip)
				@add_font_array.push font_to_add.strip
			end
		end
		if @add_font_array != [] || @delete_font_array != []
			@ckeditor_path = ENV['PWD'] + '/app/assets/javascripts/ckeditor'
			Dir.chdir(@ckeditor_path)
			if !File.file?("config_back.js.erb")
				if @str_end != nil
					@filetowrite = File.new("config_back.js.erb","w")
					if @add_font_array != []
						@add_font_array.each do |new_add_font|
							@filedata = @filedata.insert(@str_end,"\;"+new_add_font)
						end
					end
					@delete_font_array.each do |font_to_delete|
						if @filedata.index(font_to_delete) != nil
							@str_above_end = @filedata.index(font_to_delete).to_i - 1
							@str_above_start
							for @str_above_start in (0..@str_above_end).to_a.reverse
								if @filedata[@str_above_start] =="\'" || @filedata[@str_above_start] =="\""
									break
								end
								break if @filedata[@str_above_start] == "\;"
							end
							@str_above_start = @str_above_end - 1 if @str_above_start == nil
							@str_to_delete = (( @filedata[@str_above_start..@str_above_end].include? "\;") ? @filedata[@str_above_start..@str_above_end] : "")+font_to_delete
							@name_to_search ="config.font_names"
							@index_of_font = @filedata.index(@name_to_search)
							@datachange = @filedata[@index_of_font...@str_end]
							@new_datachange = @datachange.sub(@str_to_delete,'')
							@filedata =@filedata.sub(@datachange,@new_datachange)
							for @i in @str_start+1...@str_end
								next if @filedata[@i] == " "
								break if @filedata[@i] != "\;"
								@filedata.slice!(@i)
							end
						end
					end
					puts self.used_font
					puts  @filedata
					@filetowrite.write(@filedata)
					@filetowrite.close
					@filetocover = File.open("config.js.erb","w") rescue return
					@filetocover.write(@filedata)
					@filetocover.close
					File.delete("config_back.js.erb")
				end
			else
				@filedata1 = File.read("config.js.erb")
				@filedata2 = File.read("config_back.js.erb")
				if @filedata1.length < @filedata2.length
					@filetocover = File.open("config.js.erb","w")
					@filetocover.write(@filedata2)
					@filetocover.close
				end
				File.delete("config_back.js.erb")
			end
			Dir.chdir(Rails.root.to_s)
		end
	end
  end
  def check_eql_array(array1,array2)
	if array1.count == array2.count
		array1.each do |item|
			if !(array2.include? item)
				return false
			end
		end
		return true
	else
		return false
	end
  end
  def update_user
    User.find(update_user_id) rescue nil
  end
  def update_user=(user)
    self.update_user_id = user.id
  end
  def email_members
    MemberProfile.find(self.email_member_ids) rescue []
  end
  def email_addresses
    addresses = self.email_members.collect{|member| member.email} rescue []
    addresses = addresses +[self.other_mailaddress] if !self.other_mailaddress.blank?
    addresses.flatten
  end
  def email
    mail = Email.find(self.email_id) rescue nil
  end
  def expired?
    (self.deadline < Time.now) rescue false
  end
  def destroy_email
    mail = Email.find(self.email_id) rescue nil
    mail.destroy if !mail.nil?
  end
  def self.remove_expired_status
    self.where(:is_top => true, :top_end_date.ne => nil, :top_end_date.lt => Time.now).each do |b|
      b.is_top = false
      b.top_end_date = nil
      b.save
    end
  end
end