#!/usr/bin/python3
# vim: syntax=python


import argparse
import logging
import subprocess


class TmuxHelper():

    @staticmethod
    def get_sessions():
        try:
            sessions =  subprocess.check_output(['tmux', '-2', 'list-sessions',
                '-F', '#{session_name}'])
        except subprocess.CalledProcessError as e:
            return []
        sessions = sessions.decode('utf-8')
        return sessions.strip().split('\n')
    
    @staticmethod
    def start_session(session_name):
        subprocess.run(['tmux', 'new', '-s', session_name])


class SessionHelper():


    def __init__(self,prefix='tmx'):
        self.prefix = prefix

    def get_session_number(self,name):
        return int(name.split('_')[1])

    def make_session_name(self,number):
        return f'{self.prefix}_{number}'

    def is_session(self,name):
        return name.startswith(self.prefix)

    def find_next_session_number(self,session_list=None):
        if session_list is None:
            session_list =  TmuxHelper.get_sessions()
            session_list = [s for s in session_list if session_helper.is_session(s)]
            logging.debug(f'{session_list}')
        for idx , name in enumerate(session_list):
            logging.debug(f'{idx}: {name}')
            if self.get_session_number(name) - 1 > idx:
                return idx + 1
        return len(session_list) + 1


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--start','-s',action='store_true',default=False)
    parser.add_argument('--prefix','-p',default='tmx',help='default prefix (tmx)')
    args = parser.parse_args()

    logging.basicConfig(level=logging.WARNING if args.start else logging.DEBUG)
    session_helper = SessionHelper(args.prefix)

    session_number = session_helper.find_next_session_number()
    session_name = session_helper.make_session_name(session_number)

    if args.start:
        TmuxHelper.start_session(session_name)
    else:
        logging.debug(f'Make session: {session_name}')

