#!/usr/bin/env python
import os.path
import ffmpeg
from datetime import datetime
from _time_and_date_utils import convert_from_seconds

class AudioFile:
    def __init__(self,path_file_name,*args,**kwargs):
        # super(AudioFile, self).__init__(*args, **kwargs)
        self.path_file_name         = path_file_name
        self.probe                  = ffmpeg.probe(self.path_file_name)
        self.audio_capture_date     = self.get_audio_capture_date()
        self.video_stream = None
        self.audio_stream = None
        self.format_stream = None

        for i in self.probe['streams']:
            if self.video_stream is None:
                if 'video' == i['codec_type'].lower():
                    self.video_stream       = i
            if self.audio_stream is None:
                if 'audio' == i['codec_type'].lower():
                    self.audio_stream       = i
        try:
            self.format_stream          = self.probe['format']
        except AttributeError as e:
            print(f"{e}: Audio file has no format string")
            self.format_stream = None
        self.stream                 = {}

    def get_audio_capture_date(self):
        #TODO: refactor this try/except logic.
        stamp = None
        if self.format_stream is not None:
            try:
                stamp = datetime.strptime(
                    self.format_stream['tags']['date'],'%Y-%m-%d')
            except KeyError:
                try:
                    stamp = datetime.fromtimestamp(os.path.getctime(self.path_file_name))
                except:
                    stamp = datetime.strptime(
                        str('1900:01:01 00:00:00'),
                        '%Y:%m:%d %H:%M:%S'
                    )
        return stamp

    def get_audio_meta(self):
        self.stream = {
            'audio': {
                'audio_channels':       self.audio_stream['channels'],
                'bits_per_sample':      self.audio_stream['bits_per_raw_sample'],
                'codec_long_name':      self.audio_stream['codec_long_name'],
                'duration':             convert_from_seconds(float(self.audio_stream['duration'])),
                'encoding_brand':       self.format_stream['tags']['encoded_by'],
                'sample_rate':          self.audio_stream['sample_rate']
            },
            'video': {},
            'format': {}
        }

        return self.stream