#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/6/4 13:42
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: m3u8generate.py
@Contact: chanjunkai@163.com
"""
import logging

logger = logging.getLogger(__name__)

class PlaylistGenerator(object):
    def __init__(self, playlist_entries=None, version=3):
        if playlist_entries == None:
            # raise StandardError
            pass
        self.end_playlist = True
        self.playlist_entries = playlist_entries
        self.version = version
        self.sequence = 0
        self.duration = self.duration()

    def _generate_playlist(self):
        playlist = "{}\n{}{}".format(self._m3u8_header_template(), self._generate_playlist_entries(), self._end_list())

        return playlist

    def _generate_playlist_entries(self):
        playlist = ""
        for entry in self.playlist_entries:
            playlist += "#EXTINF:{duration},\n{media}\n".format(duration=float(entry['duration']), media=(entry['name']))

        return playlist.replace(" ", "")


    def _generate(self):
        return self._generate_playlist()

    def _m3u8_header_template(self):
        header = "#EXTM3U\n#EXT-X-VERSION:{version}\n#EXT-X-TARGETDURATION:{duration}\n#EXT-X-PLAYLIST-TYPE:VOD".format(version=self.version,duration=self.duration).strip()
        # header = "#EXTM3U\n#EXT-X-VERSION:{version}\n#EXT-X-MEDIA-SEQUENCE:{sequence}\n#EXT-X-TARGETDURATION:{duration}\n#EXT-X-PLAYLIST-TYPE:VOD".format(version=self.version, sequence=self.sequence, duration=self.duration).strip()

        # if self.end_playlist:
        #     return "{}\n#EXT-X-ENDLIST".format(header)
        # else:
        #     return header
        return header

    def _end_list(self):
        return "#EXT-X-ENDLIST"

    def duration(self):
        duration_total = 0
        for entry in self.playlist_entries:
            if 'duration' in entry:
                try:
                    duration_total += float(entry['duration'])
                except Exception as e:
                    logger.exception(e)

        return duration_total

    def generate(self):
        """
        This is a proxy for _generate makes it
        difficult to edit the real method for future.
        """
        return self._generate()

#
# playlist_entries = [
#     {
#         'name':  "Awesomevideo_001.mp4",
#         'duration': '10.04',
#     },
#     {
#         'name': "xxx.ts",
#         'duration': '30'
#     }
#
# ]
# playlist = PlaylistGenerator(playlist_entries).generate()
# #
# print(playlist)