#!/usr/bin/env python2
# vim: set ts=4 sw=4 expandtab sts=4:
# Copyright (c) 2013-2014 Christian Geier & contributors
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import sys

try:
    from setproctitle import setproctitle
except ImportError:
    setproctitle = lambda x: None

from khal import ConfigurationParser
from khal import controllers
from khal import capture_user_interruption

capture_user_interruption()

# setting the process title so it looks nicer in ps
# shows up as 'khal' under linux and as 'python: khal (python2.7)'
# under FreeBSD, which is still nicer than the default
setproctitle('ikhal')

# Read configuration.
conf_parser = ConfigurationParser('khal is a CalDAV based calendar')
conf = conf_parser.parse()


if conf is None:
    sys.exit(1)

if conf.debug:
    conf_parser.dump(conf)

if conf.list_accounts:
    for name in conf.accounts:
        print(name)
    sys.exit()

# TODO move this into the init
from khal import khalendar, backend
dbtool = backend.SQLiteDb(conf)

collection = khalendar.CalendarCollection()

for calendar_name in conf.sync.accounts:
    cal_conf = conf.accounts[calendar_name]
    collection.append(khalendar.Calendar(
        name=calendar_name,
        dbtool=dbtool,
        resource=cal_conf['resource'],
        username=cal_conf['user'],
        password=cal_conf['password'],
        auth=cal_conf['auth'],
        ssl_verify=cal_conf['ssl_verify'],
        server_type=cal_conf['server_type'],
        readonly=cal_conf['readonly'],
        color=cal_conf['color'],
        unicode_symbols=conf.default.unicode_symbols,
        local_timezone=conf.default.local_timezone,
        default_timezone=conf.default.default_timezone
    ))


if conf.syncrun:
    sys.exit(collection.sync())
elif conf.new:
    controllers.NewFromString(conf)
else:
    controllers.Display(collection,
                        firstweekday=conf.default.firstweekday,
                        encoding=conf.default.encoding)
