#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    @copyright: 2008 Lari Huttunen
    @license: MIT <http://www.opensource.org/licenses/mit-license.php>
"""
import sys
import socket
import optparse
import bluetooth
from opencollab.meta import Metas
from opencollab.wiki import CLIWiki, WikiFailure
from opencollab.util.config import parseOptions
from opencollab.util.wiki import importMetas


def main():
    parser = optparse.OptionParser()
    parser.add_option("-l", "--last-edit-wins",
        action="store_true", dest="lasteditwins", default=False,
        metavar="LAST-EDIT-WINS", help="Replace meta keys and values with LAST-EDIT-WINS semantics.")
    parser.set_usage("%prog [options]")
    metas = Metas()
    failed = []
    ops = {}
    sect = "bluetooth"
    ops = parseOptions(parser, sect, template=True, category=True)
    url = ops["creds"]["url"]
    verbose = ops[sect]["verbose"]
    x509 = ops[sect]["x509"]
    x509_ca_file = ops[sect]["x509_ca_file"]
    template = ops[sect]["template"]
    if template is None:
        template = "IdentityTemplate"
    category = ops[sect]["category"]
    if category is None:
        template = "CategoryIdentity"
    replace = ops[sect]["lasteditwins"]
    while True:
        try:
            collab = CLIWiki(ssl_verify_cert=x509, ssl_ca_certs=x509_ca_file, **ops['creds'])
        except WikiFailure:
            print "ERROR: Authentication failed."
        except (UnicodeError, socket.gaierror):
            sys.exit("ERROR: Not a valid URL.")
        else:
            break
    if verbose:
        print "NOTE: Resolving BlueTooth services."
    services = bluetooth.find_service()
    for svc in services:
        host = svc["host"]
        name = svc["name"]
        if name is not None:
            metas[host]["service name"].add(name)
        description = svc["description"]
        if description is not None:
            metas[host]["description"].add(description)
        provider = svc["provider"]
        if provider is not None:
            metas[host]["provider"].add(provider)
        protocol = svc["protocol"]
        if protocol is not None:
            metas[host]["protocol"].add(protocol)
        port = svc["port"]
        if port is not None:
            metas[host]["channel/psm"].add(unicode(port))
        #for sc in svc["service-classes"]:
        #    if sc is not None:
        #        metas[host]["service class"].add(unicode(sc))
        #for pr in svc["profiles"]:
        #    if pr is not None:
        #        metas[host]["profile"].add(unicode(pr))
        if svc["service-id"] is not None:
            metas[host]["service id"].add(repr(svc["service-id"]))
        if category is not None:
            for page in metas:
                metas[page]["category"].add(category)
    if verbose:
        print "NOTE: Importing metas to", url
    failed = importMetas(collab, metas, template, verbose, replace)
    if failed:
        for page in failed:
            if verbose:
                print "ERROR uploading:",  page, repr(metas[page])
            else:
                print "ERROR uploading:", page

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print "Script interrupted via CTRL-C."

