# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors.  See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import tempfile
import os

from mediagoblin import mg_globals as mgg
from mediagoblin.processing import create_pub_filepath, BadMediaFail

from mediagoblin.media_types.audio.transcoders import AudioTranscoder, \
    AudioThumbnailer

_log = logging.getLogger(__name__)

def sniff_handler(media_file, **kw):
    try: 
        transcoder = AudioTranscoder()
        data = transcoder.discover(media_file.name)
    except BadMediaFail:
        _log.debug('Audio discovery raised BadMediaFail')
        return False

    if data.is_audio == True and data.is_video == False:
        return True

    return False

def process_audio(entry):
    audio_config = mgg.global_config['media_type:mediagoblin.media_types.audio']

    workbench = mgg.workbench_manager.create_workbench()

    queued_filepath = entry.queued_media_file
    queued_filename = workbench.localized_file(
        mgg.queue_store, queued_filepath,
        'source')

    ogg_filepath = create_pub_filepath(
        entry,
        '{original}.webm'.format(
            original=os.path.splitext(
                queued_filepath[-1])[0]))

    transcoder = AudioTranscoder()

    with tempfile.NamedTemporaryFile() as ogg_tmp:

        transcoder.transcode(
            queued_filename,
            ogg_tmp.name,
            quality=audio_config['quality'])

        data = transcoder.discover(ogg_tmp.name)

        _log.debug('Saving medium...')
        mgg.public_store.get_file(ogg_filepath, 'wb').write(
            ogg_tmp.read())

        entry.media_files['ogg'] = ogg_filepath

        entry.media_data['audio'] = {
            u'length': int(data.audiolength)}

    if audio_config['create_spectrogram']:
        spectrogram_filepath = create_pub_filepath(
            entry,
            '{original}-spectrogram.jpg'.format(
                original=os.path.splitext(
                    queued_filepath[-1])[0]))

        with tempfile.NamedTemporaryFile(suffix='.wav') as wav_tmp:
            _log.info('Creating WAV source for spectrogram')
            transcoder.transcode(
                queued_filename,
                wav_tmp.name,
                mux_string='wavenc')

            thumbnailer = AudioThumbnailer()

            with tempfile.NamedTemporaryFile(suffix='.jpg') as spectrogram_tmp:
                thumbnailer.spectrogram(
                    wav_tmp.name,
                    spectrogram_tmp.name,
                    width=mgg.global_config['media:medium']['max_width'])

                _log.debug('Saving spectrogram...')
                mgg.public_store.get_file(spectrogram_filepath, 'wb').write(
                    spectrogram_tmp.read())

                entry.media_files['spectrogram'] = spectrogram_filepath

                with tempfile.NamedTemporaryFile(suffix='.jpg') as thumb_tmp:
                    thumbnailer.thumbnail_spectrogram(
                        spectrogram_tmp.name,
                        thumb_tmp.name,
                        (mgg.global_config['media:thumb']['max_width'],
                         mgg.global_config['media:thumb']['max_height']))

                    thumb_filepath = create_pub_filepath(
                        entry,
                        '{original}-thumbnail.jpg'.format(
                            original=os.path.splitext(
                                queued_filepath[-1])[0]))

                    mgg.public_store.get_file(thumb_filepath, 'wb').write(
                        thumb_tmp.read())

                    entry.media_files['thumb'] = thumb_filepath
    else:
        entry.media_files['thumb'] = ['fake', 'thumb', 'path.jpg']
            
    mgg.queue_store.delete_file(queued_filepath)

    entry.save()
