#!/usr/bin/env python3
import os
from os.path import isfile, join


class DList(object):
    def __init__(self):
        super().__init__()
        self.dlist = {}  # dlist information
        self.deployments = {}

    def clear_dlist(self):
        self.dlist = {}

    def walkserver(self, path, vh):
        """Locate *.dlist files on LRAUV server.
        
        :param path: path to LRAUV folder (string)
        :param vh: vehicle to process (string) 
        :return: update class attribute deployments (dictionary vehicle: year: [*.dlist files])
        
        """
        # add vehicle name do deployments dictionary if new
        if vh not in self.deployments.keys():
            self.deployments[vh] = {}

        # locate year folders in missionlogs folder
        folder_name = os.path.join(path, vh, "missionlogs")
        yr = [f for f in os.listdir(folder_name) if f.isdigit()]

        for y in yr:
            fname = os.path.join(folder_name, y)
            onlyfiles = [f for f in os.listdir(fname) if isfile(join(fname, f))]  # locate files while ignoring folders
            list_name = [s for s in onlyfiles if ".dlist" in s]  # list only *.dlist
            self.deployments[vh][y] = list_name

    def parse_dlist(self, dlist_path):
        """Extract list of deployment logs and metadata from .dlist files.
        
        :param dlist_path: path to .dlist file (string) 
        :return: update class attribute deployments (dictionary)
        
        """
        with open(dlist_path, 'r') as d:
            dlist_lines = [line.strip() for line in d]

        # vehicle
        vehicle = next(vh for vh in self.deployments.keys() if vh in dlist_path)
        self.dlist['vehicle'] = vehicle

        # year
        self.dlist['year'] = next(yr for yr in self.deployments[vehicle].keys() if yr in dlist_path)

        # deployment
        self.dlist['dep'] = dlist_path[-23:-6]

        # deployment name
        try:
            key, value = dlist_lines[0].split(': ', 1)
            self.dlist['name'] = value.strip()
        except ValueError:
            self.dlist['name'] = ''

        # list deployment logs
        self.dlist['log'] = [log for log in dlist_lines if not log.startswith('#') and log]

