#!/usr/bin/env python
#
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
# This component and the accompanying materials are made available
# under the terms of "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
#
# Initial Contributors:
# Nokia Corporation - initial contribution.
#
# Contributors:
#
# Description: 

import os
import logging
import codecs

from optparse import OptionParser, OptionGroup

import cone_common
from cone.public import api, plugin, utils, exceptions, container

VERSION = '1.0'

logger = logging.getLogger('cone')
elems = {
'Type': 0,
'Name': 1,
'ParentFolderName': 2,
'URL': 3,
'AccessPoint': 4,
'UserName': 5,
'Password': 6,
'ReadOnly': 7,
'FactoryItem': 8,
'ContextId': 9,
'Preferred': 10 
    }
    
def main():
    parser = OptionParser(version="%%prog %s" % VERSION)
  
    parser.add_option("-c", "--configuration",\
                        dest="configuration",\
                        help="defines the name of the configuration for the action",\
                        metavar="CONFIG")
  
    parser.add_option("-v", "--verbose",\
                      dest="verbose",\
                      help="Print error,warning and information on system out. \
                      Possible choises: Default is 3.\
                                     NONE          0.\
                                     CRITICAL      1\
                                     ERROR         2\
                                     WARNING       3\
                                     INFO          4\
                                     DEBUG         5\
                                     ",\
                      default=3,\
                      metavar="LEVEL")
    parser.add_option("-p", "--project",\
                       dest="project",\
                       help="defines the location of current project. Default is the current working directory.",\
                       default=".",\
                       metavar="STORAGE")
    
    bgroup = OptionGroup(parser, 'Import browser bookmarks options',
                    'The import_browserbookmarks functionality is meant to import browser bookmarks to a given configuration.')
  
    bgroup.add_option("-i", "--input",\
                   dest="input",\
                   type="string",
                   help="input BrowserBookmarks file for the importing.",
                   metavar="FILE",\
                   default=None)
  
    layers = None
    current = None

    parser.add_option_group(bgroup)
    (options, args) = parser.parse_args()

    api.get_console_logger().setLevel(cone_common.get_log_level(options.verbose))

    if not options.input:
        parser.error("Input file must be given!")

    logger.info('Open file %s.' % options.input)
    

    current = api.Project(api.Storage.open(options.project,"a"))
    active_root = current.get_storage().get_active_configuration()
    if not options.configuration:
        if active_root == "":
            parser.error("configuration must be given")
        else:
            logging.getLogger('cone').info('No configuration given! Using active root configuration %s' % active_root)
            options.configuration = active_root
    config  = current.get_configuration(options.configuration)
    dview = config.get_default_view()
    bookmarkfea = dview.get_feature('BookmarkItems.BookmarkItem')
    
    inputfile = codecs.open(options.input,encoding="utf16")
    firstelem = True
    for line in inputfile.readlines():
        # skip comments 
        data = line.split('#',1)
        dataelem = data[0]
        dataelem = dataelem.strip()
        dataelem = dataelem.rstrip('\n')
        
        if dataelem != "":       
            # Split the datarow in to data elems 
            #print "DATAELEM: %s!" % dataelem
            dataelems = dataelem.split(',')
            print "Elem found %s" % str(dataelems[elems['Name']])
            # Build the new data sequence
            browserseq = []
            for feaname in bookmarkfea.list_features():
                try:
                    browserseq.append(str(dataelems[elems[feaname]]))
                except IndexError:
                    pass
                
            print browserseq
            if firstelem:
                bookmarkfea.add_sequence(browserseq, policy=container.REPLACE)                  
                data = bookmarkfea.get_data()[-1]
                data._get_data().policy = 'replace'
                firstelem = False
            else:
                bookmarkfea.add_sequence(browserseq, policy=container.APPEND)

    config.save()        
                
    logger.info('Done!')
    
if __name__ == "__main__":
    main()


