require "dropbox_sdk"

module Dropscreen
  class Client

    attr_accessor :client

    def initialize opts
      @token = ENV['DROPBOX_ACCESS_TOKEN']
      @remote_base_dir = opts[:remote_base_dir] || '/'
      @local_base_dir = opts[:local_base_dir] || '/'
      @client = DropboxClient.new @token
    end

    def push(src, dest=src)
      @client.file_create_folder(File.join(@remote_base_dir, dest)) unless exists? dest
      files = Dir.entries(File.join(@local_base_dir, src)).delete_if { |filename| filename == '.' or filename == '..' or filename == '.DS_Store' }

      puts "Pushing #{files.size} files to Dropbox"

      files.each do |filename|
        file = open(File.join(@local_base_dir, src, filename))
        dropbox_file_name = File.basename(filename)

        @client.put_file(File.join(@remote_base_dir, dest, dropbox_file_name), file, true)
      end

      puts "Done pushing #{files.size} files to Dropbox"
    end

    def exists? path
      fullpath = File.join(@remote_base_dir,path)
      begin
        metadata = @client.metadata(fullpath)
        return not(metadata['is_deleted'])
      rescue DropboxError => e
        if e.message.include? 'not found'
          return false
        else
          raise e
        end
      end
    end

    def pull(src, dest=src, browser_name)
      dest = File.join(@local_base_dir, dest)
      FileUtils.mkdir_p(dest) unless File.exists?(dest)
      files = @client.metadata(File.join(@remote_base_dir, src))['contents']

      file_count = 0

      files.each do |file|
        if (file['path']).include?("#{browser_name}")
          basename = File.basename(file['path'])
          destination_filename = File.join(dest, basename)
          contents = @client.get_file(file['path'])

          open(destination_filename, 'wb') {|f| f.puts contents }
          file_count += 1
        end
      end

      puts "Done getting #{file_count} files from Dropbox"
    end

    def remove path
      is_deleted = exists?(path) ? @client.file_delete(File.join(@remote_base_dir, path))['is_deleted'] : true
      return is_deleted
    end

  end
end
