require 'colored2'
require 'thor'
require 'fileutils'
require 'psych'
require 'yaml'

module YkCommand
  class CLI < Thor
    include Thor::Actions

    CONFIG_FILE = '.YKModuleFilesConfig.yml'.freeze

    desc 'create', '开始配置'
    method_option :create, aliases: '-c'
    def create(path = nil)
      path = Dir.pwd if path.nil?

      say '模块名:', :green
      config_file_path = "#{path}/#{CONFIG_FILE}"
      config = File.exist?(config_file_path) ? YAML.load_file(config_file_path) : {}
      input_name = ask("Project name [#{config[:project]}] ?")

      if input_name != ''
        @name = input_name
        config[:project] = input_name if input_name != config[:project]
      else
        @name = config[:project]
      end

      File.open(config_file_path, 'w') do |f|
        f.write config.to_yaml
      end

      @final_path = "#{path}/#{@name}"

      if File.exist?(@final_path.to_s)
        say "#{@final_path} 已存在:", :red
      else
        prepare_folder
        read_config(path)

        if File.exist?("#{@final_path}/configure")
          system("#{@final_path}/configure", @name, @lang, @class_prefix, *@additional_args)
        else
          say 'Template does not have a configure file', :red
        end

        yk_module_folders
        yk_template_files

      end
    end

    no_commands do
      def read_config(path)
        config_file_path = "#{path}/#{CONFIG_FILE}"
        config = File.exist?(config_file_path) ? YAML.load_file(config_file_path) : {}

        project = @name
        say '语言:', :green
        language = ask("Project language [#{config[:language]}] ?", limited_to: ['objc', 'swift', ''])
        say '类名前缀:', :green
        class_prefix = ask("Class prefix [#{config[:class_prefix]}] ?")
        say '文件作者:', :green
        author = ask("Author [#{config[:author]}] ?")

        config[:project]      = project.empty?      ? config[:project] || ''      : project
        config[:language]     = language.empty?     ? config[:language] || 'objc' : language
        config[:class_prefix] = class_prefix.empty? ? config[:class_prefix] || '' : class_prefix
        config[:author]       = author.empty?       ? config[:author] || ''       : author

        File.open(config_file_path, 'w') do |f|
          f.write config.to_yaml
          # f.write YAML.to_yaml(config)
        end

        @module = @name
        @class_prefix = config[:class_prefix]
        @prefixed_module = config[:class_prefix] + @module
        @project         = config[:project]
        @author          = config[:author]
        @date            = Time.now.strftime('%d/%m/%y')
        @lang = config[:language]
        @prefixed_module = "YK#{@name}"
      end

      def prepare_folder
        host_a = 'yeah'
        host_b = 'ka'
        template_repo_url = "http://gitlab.#{host_a}#{host_b}.com/App/iOS/YKComponents/YKProjectTemplate.git"
        system("git clone #{template_repo_url} #{@final_path}")

        # FileUtils.remove_dir(@final_path, true)
        # FileUtils.cp_r('/Users/imacn24/Documents/dev/YKProjectTemplate', @final_path)
        # FileUtils.remove_dir("#{@final_path}/.git", true)
      end

      def yk_module_folders
        class_folder_path = "#{@final_path}/#{@name}/Classes"

        first_level_folders = %w[Public Private]
        public_level_folders = ['Register']
        private_level_folders = %w[Business Category Vendor Tools]

        first_level_folders.each do |folder|
          path = "#{class_folder_path}/#{folder}"
          empty_directory path
        end

        public_level_folders.each do |folder|
          path = "#{class_folder_path}/Public/#{folder}"
          empty_directory path
        end

        private_level_folders.each do |folder|
          path = "#{class_folder_path}/Private/#{folder}"
          empty_directory path
          if folder == 'Business'

          else
            system "touch \"#{path}/EmptyFile.m\""
          end


        end
      end

      CLI.source_root(File.dirname(__FILE__))

      def yk_template_files
        register_path = "#{@final_path}/#{@name}/Classes/Public/Register"
        registger = {
          'RouterRegister.h'     => 'RouterRegister',
          'RouterRegister.m'     => 'RouterRegister',
          'ServiceRegister.h'     => 'ServiceRegister',
          'ServiceRegister.m'     => 'ServiceRegister'
        }

        registger.each do |file_name, _folder|
          final_file = "#{register_path}/#{@prefixed_module}#{file_name}"
          template "#{__dir__}/template/objc/#{file_name}", final_file
        end

        template_code_filename = ['ServiceProtocol.h','RouterDefine.h']
        public_folder_path = "#{@final_path}/#{@name}/Classes/Public"
        template_code_filename.each do |file_name|
          final_file = "#{public_folder_path}/#{@prefixed_module}#{file_name}"
          source = "#{__dir__}/template/objc/#{file_name}"
          template source, final_file
        end


        business_demo_path = "#{@final_path}/#{@name}/Classes/Private/Business"
        demo_replace_file = ['DemoViewController.h','DemoViewController.m','DemoViewModel.h','DemoViewModel.m']
        demo_replace_file.each do |file_name|
          final_file = "#{business_demo_path}/#{@prefixed_module}#{file_name}"
          source = "#{__dir__}/template/objc/demo/#{file_name}"
          template source, final_file
        end



        Dir.chdir("#{@final_path}/Example") do
          system 'pod install --silent'
          system "open './#{@name}.xcworkspace'"
        end
      end

    end


  end
end