#! /usr/bin/env ruby
$KCODE = 'UTF-8'
require 'jcode'
require File.dirname(__FILE__) + '/lib/base'
require File.dirname(__FILE__) + '/lib/csv'

class PasswordWalletImporter < Importer
  
  def process_line(line)
    line = line.gsub(/¬/, "1PasswordNewLineCharacter")
    # Not sure what this character is, but it shows up in
    # the Secure Notes notes field sometimes.
    line = line.gsub(/Â/, "1PasswordNewLineCharacter")
    items = CSV::parse_line(line, "\t")
    if (items.size < 5)
      @errors << "Failed to parse line '#{line}'"
      return
    end
    
    title = items[0] || ""
    url = items[1] || ""
    username = items[2] || ""
    password = items[3] || ""
    notes = items[4] || ""

    notes = notes.gsub("1PasswordNewLineCharacter", "\n")
    category = ""
    if items.size >= 6
      category = items[5] || ""
    end
    
    item = nil
  	if (url == nil || url.length < 4) 
      item = SecureNote.new
      item.title = title
      item.notes = "URL: #{url}\nUsername: #{username}\nPassword: #{password}\n-----\n#{notes}"
  	else
      item = WebForm.new
      item.name = title
      item.url = url
      item.add_login(username, password)
      item.notes = notes
    end
    
    item.folderPath = category
    add_item(item)
    
  end
  
end

PasswordWalletImporter.new.run
