import os.path
import sys

from _audio import AudioFile
from _hashing import hash_path
from _video import VideoFile
from _photo import PhotoFile
from _file_stuff import (get_file_name,
                         get_file_ext,
                         get_dotted_file_ext)
from datetime import datetime

class MediaFile:
    def __init__(self,
                 path_file_name,
                 config,
                 event_name,
                 *args,**kwargs):
        # super(MediaFile,self).__init__(*args,**kwargs)
        self.path_file_name = path_file_name
        self.config = config
        self.event_name = str(event_name)
        self.store_originals = self.config['store_originals']
        self.src_dir = self.config['folders']['source']['base']
        self.base_dst_dir = self.config['folders']['destination']['base']
        self.source_path_hash               = hash_path(self.path_file_name)
        self.file_name                      = get_file_name(self.path_file_name)
        self.dotted_file_ext                = get_dotted_file_ext(self.file_name)
        self.file_ext                       = get_file_ext(self.file_name)
        self.file_type                      = self.get_file_type()
        self.capture_date                   = self.get_capture_date()
        self.capture_date_year              = self.capture_date[0]
        self.capture_date_month             = self.capture_date[1]
        self.capture_date_day               = self.capture_date[2]
        self.dst_dir                        = self.set_destination_path()
        self.destination_originals_path     = ''
        self.media                          = {}
        self.media_meta                     = self.get_media_meta()

        # video_media = VideoFile(path_file_name=self.path_file_name)
        # audio_media = AudioFile(path_file_name=self.path_file_name)
        # photo_media = PhotoFile(path_file_name=self.path_file_name)

    def get_file_type(self):
        """ determine if the extension is in the list of file types """
        for t in self.config['file_types']:
            for e in self.config['file_types'][t]:
                if self.file_ext.lower().endswith(e.lower()):
                    return t

    def set_destination_path(self):
        """
        set the destination path for the file
        base dir structure is:
            base_dst_dir/YYYY/YYYY-MM/YYYY-MM-DD[-event_name]
        """
        p1 = os.path.join(self.base_dst_dir,self.capture_date_year)
        p2 = f'{self.capture_date_year}-{self.capture_date_month}'
        p3 = f'{self.capture_date_year}-{self.capture_date_month}-{self.capture_date_day}'

        p                                               = f'{p1}/{p2}/{p3}'         # <--- Dumb.
        if self.event_name:
            p4                                          = '-' + self.event_name
            p                                           = os.path.join(p,p4)

        if self.file_type == 'image':
            p                                           = os.path.join(p,'PHOTO')
            if self.file_ext.lower() in ('jpg', 'jpeg'):
                if self.store_originals is True:
                    self.destination_originals_path     = os.path.join(
                        p,
                        self.config['folders']['originals'],
                        'JPG'
                    )
                p                                       = os.path.join(p, 'JPG')
            else:
                if self.store_originals is True:
                    self.destination_originals_path     = os.path.join(
                        p,
                        self.config['folders']['originals'],
                        'RAW')
                p                                       = os.path.join(p,'RAW')
        elif self.file_type == 'video':
            p = os.path.join(p,'VIDEO')
        elif self.file_type == 'audio':
            p = os.path.join(p,'AUDIO')

        return p

    def get_capture_date(self):
        """ get capture date from meta """

        if self.file_type == 'image':
            photo_media = PhotoFile(path_file_name=self.path_file_name)
            stamp                                       = photo_media.photo_capture_date
        elif self.file_type == 'video':
            video_media = VideoFile(path_file_name=self.path_file_name)
            stamp                                       = video_media.get_video_capture_date()
        elif self.file_type == 'audio':
            audio_media = AudioFile(path_file_name=self.path_file_name)
            stamp                                       = audio_media.get_audio_capture_date()
        else:
            try:
                stamp                                   = datetime.fromtimestamp(
                    os.path.getctime(
                        self.path_file_name
                    )
                )
            except:
                print('end of the road for finding the date.')
                sys.exit()

        year                                            = stamp.strftime("%Y")
        month                                           = stamp.strftime("%m")
        day                                             = stamp.strftime("%d")
        return year, month, day

    def get_media_meta(self):
        self.media = {
            'date': {
                'capture_date': {
                    'y':                            self.capture_date_year,
                    'm':                            self.capture_date_month,
                    'd':                            self.capture_date_day
                }
            },
            'event': {
                'name':                             self.event_name
            },
            'extension':                            self.file_ext,
            'folders': {
                'destination':                      self.dst_dir,
                'destination_original':             self.destination_originals_path,
                'source_path':                      self.src_dir
            },
            'name':                                 self.file_name,
            'source_path_hash':                     self.source_path_hash,
            'file_type':                            self.file_type
        }

        if self.file_type == 'video':
            video_media                             = VideoFile(path_file_name=self.path_file_name)
            self.media['video_meta']                = video_media.video_meta()
            self.media['image_meta']                = None
            self.media['audio_meta']                = None

        if self.file_type == 'image':
            photo_media                             = PhotoFile(path_file_name=self.path_file_name)
            self.media['image_meta']                = photo_media.get_photo_meta()
            self.media['video_meta']                = None
            self.media['audio_meta']                = None

        if self.file_type == 'audio':
            audio_media                             = AudioFile(path_file_name=self.path_file_name)
            self.media['audio_meta']                = audio_media.get_audio_meta()
            self.media['image_meta']                = None
            self.media['video_meta']                = None

        print(f'MediaFile, self.media: {self.media}')
        return self.media