import itertools
import novaclient.exceptions
import os
import paramiko
import pprint
import socket
import sys
import time
import yaml

from novaclient.v1_1 import client

from config import get_config
from parser import get_parser


class Devstork(object):

    def __init__(self, config):
        """
        Inits the Devstork instance.
        Saves the configuration and creates a novaclient instance.

        @param config - Dictionary

        """
        self._config = config
        self._client = client.Client(**self._config.get('auth', {}))

    def _create_start(self):
        """
        Signals that creation has started.
        Saves the current time for use with timeout checks.

        """
        self._create_started = time.time()

    def _check_create_time(self):
        """
        Checks the current time against the creation time + the timeout.
        Raises an exception if the current time has exceeded the timeout.

        """
        # Deletes will not have a create started timestamp
        if not hasattr(self, '_create_started'):
            return True

        timeout = self._config['create_timeout']
        if timeout > 0 and time.time() > self._create_started + timeout:
                raise Exception(
                    "VM Creation timed out. Took longer than %s seconds"
                    % timeout
                )

    def get_server(self):
        """
        Uses the nova client to query for a server.
        Uses the uuid saved in the file specified by the config.

        @returns Server|None

        """
        if os.path.isfile(self._config['id_file']):
            with open(self._config['id_file']) as f:
                data = yaml.safe_load(f)
            try: