$:.push File.expand_path("../lib", __FILE__)

# Maintain your gem's version:
require "archive/version"
require 'json'
bundle_update_flag = ARGV[0]=='update' || ARGV[0]=='install'
if bundle_update_flag
  env_pwd = ENV['PWD']
  begin
    require ::File.expand_path('app/helpers/bundler_helper.rb',  env_pwd)
    extend BundlerHelper
  rescue LoadError
    def bundler_with_clean_env
      if block_given?
        if Bundler.respond_to?(:with_unbundled_env)
          Bundler.with_unbundled_env(&Proc.new)
        else
          Bundler.with_clean_env(&Proc.new)
        end
      end
    end
  end
  app_path = File.expand_path(__dir__)
  template_path = env_pwd + '/app/templates'
  all_template = Dir.glob(template_path+'/*/')
  module_name = 'archive'
  default_module_info = JSON.parse(File.read("#{app_path}/modules/#{module_name}/info.json")).map{|k,v| [k, v.sort_by{|h| h["filename"].to_i}]}.to_h rescue []
  all_template.each do |folder|
    if !folder.include?('mobile')
      info_json_file = "#{folder}modules/#{module_name}/info.json"
      if File.exist?(info_json_file)
        begin
          file_text = File.read(info_json_file) rescue ""
          encode_file_text = file_text.encode("UTF-8", "UTF-8", invalid: :replace, replace: "???")
          next if (encode_file_text.include?("???") rescue true)
          info = JSON.parse(encode_file_text) rescue {}
          flag = (info.count != 0 rescue false)
          if flag
            idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
            update_flags = []
            puts "Checking #{module_name} templates"
            default_module_info.each do |info_type, default_sub_info|
              update_flag = false
              file_prefix = (info_type == 'widgets' ? '_' : '')
              sub_info = info[info_type].sort_by{|h| h["filename"].to_i} rescue []
              last_index = sub_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
              if last_index.nil?
                next
              end
              default_sub_info.each do |h|
                name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
                sub_info_index = (sub_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
                force_cover = (h["force_cover"] == "true")
                if sub_info_index == -1 && h["old_name"] #check with old name
                  name_without_index = h["old_name"]["zh_tw"].gsub(idx_regex,'')
                  sub_info_index = (sub_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
                  if sub_info_index != -1
                    update_flag = true
                    force_cover = true
                    sub_info[sub_info_index]["name"] = h["name"]
                  end
                end
                if sub_info_index == -1
                  update_flag = true
                  copy_h = h.dup
                  h.delete("force_cover")
                  h.delete("old_name")
                  last_index = last_index + 1
                  copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
                  copy_h["name"].keys.each do |locale|
                    copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
                  end
                  sub_info << copy_h
                  bundler_with_clean_env{%x[cp -f #{app_path}/modules/#{module_name}/#{file_prefix}#{h["filename"]}.html.erb #{folder}modules/#{module_name}/#{file_prefix}#{copy_h["filename"]}.html.erb]}
                elsif force_cover
                  bundler_with_clean_env{%x[cp -f #{app_path}/modules/#{module_name}/#{file_prefix}#{h["filename"]}.html.erb #{folder}modules/#{module_name}/#{file_prefix}#{sub_info[sub_info_index]["filename"]}.html.erb]}
                end
              end
              if update_flag
                info[info_type] = sub_info
              end
              update_flags << update_flag
            end
            if update_flags.select{|flag| flag}.count != 0
              puts "Writing json in #{info_json_file}"
              begin
                info_json = JSON.pretty_generate(info).gsub(":[",":[\n").gsub(":{",":{\n")
              rescue
                info_json = info.to_s.gsub("=>",": \n")
              end
              File.open(info_json_file,"w+"){|f| f.write(info_json)}
            end
            bundler_with_clean_env{%x[cp -rn #{app_path}/modules/#{module_name}/thumbs/* #{folder}modules/#{module_name}/thumbs/.]}
          end
        rescue => e
          puts e
          puts "There has some error when checking #{module_name} templates"
        end
      end
    end
  end
end
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
  s.name        = "archive"
  s.version     = Archive::VERSION
  s.authors     = ["Ruling Digital"]
  s.email       = ["orbit@rulingcom.com"]
  s.homepage    = "http://www.rulingcom.com"
  s.summary     = "Archive module for Orbit."
  s.description = "Archive module for Orbit"
  s.license     = "MIT"

  s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
  s.test_files = Dir["test/**/*"]
end
