require 'yaml'
require 'pathname'
module Slipway
  # The actual endpoint. production, staging ect.
  class AppEnv
    class << self
      def build_envs
        YAML.load_file(yaml_file).fetch('app_envs').map do |hash|
          new(hash)
        end
      end

      # Attributing Bundler:
      # https://github.com/bundler/bundler/blob/master/lib/bundler/shared_helpers.rb
      # Used under MIT license
      def find_file(*names)
        search_up(*names) do |filename|
          return filename if File.file?(filename)
        end
      end

      private

      def yaml_file
        find_file('slipway.yml')
      end

      # Attributing Bundler:
      # https://github.com/bundler/bundler/blob/master/lib/bundler/shared_helpers.rb
      # Used under MIT license
      def search_up(*names)
        previous = nil
        current  = File.expand_path(Pathname.pwd)
        until !File.directory?(current) || current == previous
          names.each do |name|
            filename = File.join(current, name)
            yield filename
          end
          previous = current
          current = File.expand_path('..', current)
        end
      end
    end

    attr_accessor :name, :app_name, :after_tasks, :before_tasks, :repo_name,
                  :remote_branch, :service

    def initialize(opts)
      self.name = opts.fetch('name')
      self.repo_name = opts.fetch('repo_name', 'heroku')
      self.remote_branch = opts.fetch('remote_branch', 'master')
      self.after_tasks = opts.fetch('after', [])
      self.before_tasks = opts.fetch('before', [])
      self.app_name = opts.fetch('app_name')
      self.service = opts.fetch('service', 'heroku')
    end
  end
end
