import argparse
import boto3
import sys
import json

from .channel import Channel
from .ladder_generator import Ladder_generator


def extract_data(data):
    """ Extracts values of json object generated by ffprobe.
        Example data can be found at debug/sample_input.json
    """
    try:
        streams = json.loads(data)['streams']
        input_values = {
            'audio_codec': streams[0]['codec_name'],
            'audio_sample_rate': int(streams[0]['sample_rate']),
            'audio_bitrate': int(streams[0]['bit_rate']),
            'video_codec': streams[1]['codec_name'],
            'video_profile': streams[1]['profile'],
            'video_width': int(streams[1]['width']),
            'video_height': int(streams[1]['height']),
            'video_fps': int(streams[1]['r_frame_rate'].split('/')[0]),
            'video_bitrate': round(int(streams[1]['bit_rate'])/1000)
        }
        return input_values
    except Exception as e:
        print("Invalid data")
        sys.exit()

def debug(key, data, inputType):
    data = extract_data(data)
    with open("{key}-debug.log".format(key=key), "w") as f:
        f.write("Stream key is \"{key}\" \n".format(key=key))
        f.write("Input data is: \n================\n")
        f.write(json.dumps(data, indent=4, sort_keys=True))
        f.write("\n==============\n")
        f.write("Generating channel object...\n")
        channel = Channel(key, data['video_width'], data['video_height'], data['video_fps'],\
                          data['video_bitrate'], data['audio_bitrate'], None)
        f.write("Channel status is: {status}".format(status=channel.check_status()))
        f.write("\nProposed video ladder is: \n================\n")
        ladder = Ladder_generator()
        f.write(json.dumps(ladder.generate(data['video_height'], data['video_bitrate'], \
                                           data['video_fps'], data['audio_bitrate'], []),  indent=4, sort_keys=True))
        f.write("\n==============\n")


def create_channel(key, data, inputType):
    """ Create and start a AWS Medialive Channel """
    data = extract_data(data)
    channel = Channel(key, data['video_width'], data['video_height'], data['video_fps'],\
                    data['video_bitrate'], data['audio_bitrate'], inputType)
    channel.create_channel_input()
    channel.create_channel()
    
def main():
    parser = argparse.ArgumentParser(description='Dev.')
    parser.add_argument('--action', action='store', type=str, required=True, choices=['Create', 'Delete'])
    parser.add_argument('--key', type=str)
    parser.add_argument('--data', type=str)
    parser.add_argument('--input', type=str, required=False, choices=['Pull', 'Push'])
    parser.add_argument('--debug', type=bool)
    args = parser.parse_args()
    
    if args.action == 'Create':
        if args.data == None or args.key == None:
            parser.error("Action \"Create\" needs --data and --key flags. Check -h or --help for more info.")
        if args.input != None:
            args.input = "Pull"
        if args.debug:
            debug(args.key, args.data, args.input)
        #create_channel(args.key, args.data, inputType)
    
    
