class Fontfile
  include Mongoid::Document
  include Mongoid::Timestamps

  include OrbitModel::Status
  include OrbitModel::Impression
  # encoding: utf-8
  include OrbitTag::Taggable
  include OrbitCategory::Categorizable
  field :title ,type:String ,default:""
  field :is_delete_font_file, type:String,default: 'false'
  field :old_title ,type:String ,default:""
  field :font_link ,type:String ,default:""
  field :old_font_link ,type:String ,default:""
  mount_uploader :font_file, AssetUploader
  field :font_file_name, type:String ,default:""
  field :font_dir, type:String ,default:""
  field :old_font_file_name, type:String ,default:""
  field :old_font_dir, type:String ,default:""
  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)}
  after_update :change_font_name,:set_css_link,:change_font_settings
  def change_font_settings
	if self.old_font_file_name == self.font_file_name && self.is_delete_font_file =='true'
		self.font_file_name = ""
		self.is_delete_font_file = 'false'
		self.save
	elsif self.is_delete_font_file =='true'
		self.is_delete_font_file = 'false'
	end
	template_path = ENV['PWD'] + '/app/templates'
	all_template = Dir.glob(template_path+'/*/')
	all_template.each do |folder|
		next if !Dir.exist?(folder+"partial/")
		if folder.split('/')[-1] != 'mobile'
			begin 
				Dir.chdir(folder+"partial/")
				@file_name = "_head.html.erb"
				@filetowrite
				if !File.file?(@file_name)
					@filetowrite = File.new(@file_name,"w")
					@filetowrite.close
				end
				@file_content = File.read(@file_name)
				if self.old_font_dir != '' && self.old_font_file_name != '' && self.old_font_file_name != self.font_file_name
					if self.old_font_dir != ""
						Dir.chdir(self.old_font_dir)
						File.delete(self.old_font_file_name) if File.exist?(self.old_font_file_name)
					end			
					Dir.chdir(folder+"partial/")
					@font_link_str = "<link href=\'/assets/"+"#{self.old_font_file_name}"+"\' type=\'text/css\' rel=\'stylesheet\'>"
					if @file_content.include? @font_link_str
						@file_content = @file_content.gsub(@font_link_str,'')
						@filetowrite = File.open(@file_name,"w")
						@filetowrite.write(@file_content)
						@filetowrite.close
					end
				end
				if self.old_font_link != ""&& self.old_font_link != self.font_link
					@font_link_str = "<link href=\'"+"#{self.old_font_link}"+"\' rel=\'stylesheet\'>"
					if @file_content.include? @font_link_str
						@file_content = @file_content.gsub(@font_link_str,'')
						@filetowrite = File.open(@file_name,"w")
						@filetowrite.write(@file_content)
						@filetowrite.close
					end
				end
			rescue 
				puts folder
				puts 'error copy'
			end
		end
	end
	Dir.chdir(Rails.root.to_s)
  end
  def set_css_link
	template_path = ENV['PWD'] + '/app/templates'
	all_template = Dir.glob(template_path+'/*/')
	all_template.each do |folder|
		next if !Dir.exist?(folder+"partial")
		if folder.split('/')[-1] != 'mobile'
			begin 
				Dir.chdir(folder+"partial/")
				@file_name = "_head.html.erb"
				@filetowrite
				if !File.file?(@file_name)
					@filetowrite = File.new(@file_name,"w")
					@filetowrite.close
				end
				@file_content = File.read(@file_name)
				@file_content = @file_content.force_encoding('UTF-8').gsub('%20',' ')
				if self.font_dir != '' && self.font_file_name != ''
					@font_link_str = "<link href=\'/assets/"+"#{self.font_file_name}"+"\' type=\'text/css\' rel=\'stylesheet\'>"
					@str_to_search = '/assets/'+ self.font_file_name.to_s
					if @file_content.include? @str_to_search
						
						@str_start = @file_content.index(@str_to_search)
						@istrue = 0
						@str_match = 'href'.reverse
						@index = 0
						for @i in (0...@str_start.to_i).to_a.reverse
							next if @file_content[@i] == ' ' || @file_content[@i] == '=' ||  @file_content[@i] == '\''
							if @file_content[@i] == @str_match[@index]
								@index = @index + 1
							else
								break
							end
							if @index == @str_match.length
								@istrue = 1
								break
							end
						end
						if @istrue == 0
							open(@file_name, 'a') { |f|
							  f.puts @font_link_str
							}
						end
					else
						open(@file_name, 'a') { |f|
						  f.puts @font_link_str
						}
					end
				end
				if self.font_link != ""
					@font_link_str = "<link href=\'"+"#{self.font_link}"+"\' rel=\'stylesheet\'>"
					@str_to_search = self.font_link.to_s
					if @file_content.include? @str_to_search
						@str_start = @file_content.index(@str_to_search)
						@istrue = 0
						@str_match = 'href'.reverse
						@index = 0
						for @i in (0...@str_start).to_a.reverse
							next if @file_content[@i] == ' ' || @file_content[@i] == '=' ||  @file_content[@i] == '\''
							if @file_content[@i] == @str_match[@index]
								@index = @index + 1
							else
								break
							end
							if @index == @str_match.length
								@istrue = 1
								break
							end
						end
						if @istrue == 0
							open(@file_name, 'a') { |f|
							  f.puts @font_link_str
							}
						end
					else
						open(@file_name, 'a') { |f|
						  f.puts @font_link_str
						}
					end
				end
			rescue 
				puts folder
				puts 'error copy'
			end
		end
	end
  end
  def change_font_name
	if self.old_title !="" && self.old_title != self.title
		@field = Patchfilefield.where("title"=>"patchfile").first
		@font_old_name
		@field.font_array.each do |font,istrue|
			if font == self.old_title
				@font_old_name = font
				break
			end
		end
		if @font_old_name.nil? == false
			@istrue = @field.font_array[@font_old_name]
			@field.font_array[self.title] = @istrue
			@field.font_array.delete(@font_old_name)
			@field.delete_font = @font_old_name
			@field.update
			@field = Patchfilefield.where("title"=>"patchfile").first
			@field.set_un_used_font
			@field.set_used_font
			@field.update
		end
	end
  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.update
    end
  end

end
