#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Authors: Manuel de la Pena <manuel@canonical.com>
#          Alejandro J. Cura <alecu@canonical.com>
#
# Copyright 2011 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Start the sso service on a windows machine."""

# disable the name warning and complains about twisted
# pylint: disable=C0103, E1101, F0401
import sys

from PyQt4 import QtGui
# need to create the QApplication before installing the reactor
app = QtGui.QApplication(sys.argv)
import qtreactor.qt4reactor
qtreactor.qt4reactor.install()

from twisted.internet import reactor, defer
from twisted.spread.pb import PBServerFactory
from twisted.internet.task import LoopingCall
from twisted.python import log

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.main.windows import (
    CredentialsManagement,
    LOCALHOST,
    SSOCredentials,
    SSOLogin,
    UbuntuSSORoot,
    get_activation_config,
)
from ubuntu_sso.utils import tcpactivation


logger = setup_logging("windows-ubuntu-sso-login")


def add_timeout(interval, callback, *args, **kwargs):
    """Add a timeout callback as a task."""
    time_out_task = LoopingCall(callback, *args, **kwargs)
    time_out_task.start(interval/1000, now=False)


@defer.inlineCallbacks
def main():
    """Initialize and start this process."""
    ai = tcpactivation.ActivationInstance(get_activation_config())
    port = yield ai.get_port()

    login = SSOLogin('ignored')
    creds = SSOCredentials()
    creds_management = CredentialsManagement(add_timeout, reactor.stop)
    root = UbuntuSSORoot(login, creds, creds_management)

    reactor.listenTCP(port, PBServerFactory(root), interface=LOCALHOST)


def handle_already_started(failure):
    """Handle the already started error by shutting down this process."""
    failure.trap(tcpactivation.AlreadyStartedError)
    print "Ubuntu SSO login manager already running."
    reactor.stop()


def utter_failure(failure):
    """Handle an utter failure by logging it and quiting."""
    log.err(failure)
    reactor.stop()


if __name__ == '__main__':
    d = main()
    d.addErrback(handle_already_started)
    d.addErrback(utter_failure)
    reactor.run()
