import json
import os
import socket

import requests
import shutil


class Session(object):
    """
    Class representing an Xrun session
    it is based on the directory description of the session
    """

    def __init__(self, name='anonymous', dir=None, host='localhost', user=None, base_url=None,
                 active=False, processe_pids={}, pid=None, collect_description=False):

        self.name = name
        self.dir = dir
        self.user = user
        self.host = host
        self.base_url = base_url
        self.active = active
        self.process_pids = processe_pids
        self.pid = pid

        # complement the description by parsing the directory
        if collect_description:
            self.collect_description()

    def __str__(self):
        pids_str = ', '.join('{} ({})'.format(name, pid if pid else 'stopped')
                             for pid, name in self.process_pids.items())

        return '{} ({}) - {} - nb_procs={}: {}'.format(self.name, self.pid,
                                                       ('active' if self.active else 'inactive'),
                                                       len(self.process_pids), pids_str)

    def collect_description(self):
        """
        Parse the session directory
        """
        if not os.path.isdir(self.dir):
            self.active = False

        # read json description
        path = os.path.join(self.dir, 'session.json')
        if os.path.isfile(path):
            try:
                with open(path) as fp:
                    self.__dict__.update(json.load(fp=fp))
            except:
                pass

        # get the session manager from the REST interface directly
        if self.base_url:
            try:
                r = requests.get(url=self.base_url + '/', timeout=1)
                r.raise_for_status()
                self.__dict__ = r.json()
            except:
                self.active = False


    def cleanup(self, keep_dir=False):

        # clear the directory of the manager
        if not keep_dir:
            try:
                shutil.rmtree(self.dir)
            except:
                pass


    def dump(self):
        with open(os.path.join(self.dir, 'session.json'), 'w+') as fp:
            json.dump(self.__dict__, fp=fp, indent=4)

