#! /usr/bin/env ruby
require File.dirname(__FILE__) + '/lib/base'
require File.dirname(__FILE__) + '/lib/csv'

class EWalletImporter < Importer
  attr_accessor :current_category, :current_type, :current_name, :current_data
  
  def process(lines)
    reset_current_entry

    0.upto(lines.length - 1) { |i| 
      current = lines[i]
      peek = lines[i+1]
      previous = i == 0 ? nil : lines[i-1]
      process_line(current, peek, previous)
    }
    add_current_entry_to_1p
  end

  def process_line(current, peek, previous)
    if (current =~ /^Category: (.*)$/ && peek.blank? && previous.blank?)
      add_current_entry_to_1p unless @current_name.nil?
      @current_category = $1
      return
    end
    
    if (previous.blank? && peek =~ /^Card Type/ && current =~ /Card Name (.*)/)
      add_current_entry_to_1p unless @current_name.nil?
      @current_name = $1
      @current_name = "#{@current_category}\\#{@current_name}" unless @current_category.nil?
      return
    end
    
    if (previous =~ /Card Name (.*)/ && current =~ /^Card Type (.*)$/)
      @current_type = $1
      return
    end
    
    current_data << current
  end
  
  def add_current_entry_to_1p
    @current_data.delete_at(0) if @current_data[0].blank?
    @current_data.delete_at(@current_data.length-1) if @current_data.last.blank?
    
    if @current_type == "Password"
      add_web_form
    else
      add_secure_note
    end
    
    reset_current_entry
  end
  
  def add_web_form
#    puts "Adding WebForm:\n    Name:'#{@current_name}'\n    Type:'#{@current_type}'\n    Data:#{@current_data.inspect}"
    
    system = $1 if @current_data[0] =~ /^System (.*)$/
    username = $1 if @current_data[1] =~ /^User Name (.*)$/
    password = $1 if @current_data[2] =~ /^Password (.*)$/
    url = $1 if @current_data[3] =~ /^URL (.*)$/

    if system.nil? || username.nil? || password.nil? || url.nil? 
      add_error "Malformed Password card entry; skipping card named '#{@current_name}'"
    end

    f = WebForm.new
    f.title = @current_name 
    f.title = "#{f.title} (#{system})" unless system.nil?
    f.add_login(username, password)
    f.url = url

    f.notes = ""

    4.upto(@current_data.length - 1) { |i|
      f.notes += @current_data[i] + "\n"
    }

    add_item f
  end

  def add_secure_note
    n = SecureNote.new
    n.title = @current_name
    n.notes = ""
    @current_data.each { |s|
      n.notes += s + "\n"
    }

    add_item n
  end
  
  def reset_current_entry
    @current_data = []
    @current_type = nil
    @current_name = nil
  end
end

EWalletImporter.new.run
