"""
Copyright (c) 2016, John Deutscher
Description: Sample Python script for OCR processor
License: MIT (see LICENSE.txt file for details)
Documentation : https://azure.microsoft.com/en-us/documentation/articles/media-services-video-optical-character-recognition/
"""
import os
import json
import amspy
import time
import sys
#import pytz
import urllib
import logging
import datetime
from azure import *
from azure.storage.blob import BlockBlobService
from azure.storage.blob import ContentSettings

###########################################################################################
##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER #####
###########################################################################################

# ALL CODE IN THIS DIRECTOY (INCLUDING THIS FILE) ARE EXAMPLE CODES THAT  WILL  ACT ON YOUR 
# AMS ACCOUNT.  IT ASSUMES THAT THE AMS ACCOUNT IS CLEAN (e.g.: BRAND NEW), WITH NO DATA OR 
# PRODUCTION CODE ON IT.  DO NOT, AGAIN: DO NOT RUN ANY EXAMPLE CODE AGAINST PRODUCTION AMS
# ACCOUNT!  IF YOU RUN ANY EXAMPLE CODE AGAINST YOUR PRODUCTION  AMS ACCOUNT,  YOU CAN LOSE 
# DATA, AND/OR PUT YOUR AMS SERVICES IN A DEGRADED OR UNAVAILABLE STATE. BE WARNED!

###########################################################################################
##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER #####
###########################################################################################

# Load Azure app defaults
try:
	with open('../../config.json') as configFile:
		configData = json.load(configFile)
except FileNotFoundError:
	print_phase_message("ERROR: Expecting config.json in examples folder")
	sys.exit()

account_name = configData['accountName']
account_key = configData['accountKey']
sto_account_name = configData['sto_accountName']
sto_accountKey = configData['sto_accountKey']
log_name = configData['logName']
log_level = configData['logLevel']
purge_log = configData['purgeLog']

#Initialization...
print ("\n-----------------------= AMS Py =----------------------")
print ("Azure Media Analytics -OCR v1 Sample")
print ("for details see: https://azure.microsoft.com/en-us/documentation/articles/media-services-video-optical-character-recognition/")
print ("-------------------------------------------------------\n")

#Remove old log file if requested (default behavior)...
if (os.path.isdir('./log') != True):
	os.mkdir('log')
if (purge_log.lower() == "yes"):
        if (os.path.isfile(log_name)):
                os.remove(log_name)

#Basic Logging...
logging.basicConfig(format='%(asctime)s - %(levelname)s:%(message)s', level=log_level, filename=log_name)

# Get the access token...
response = amspy.get_access_token(account_name, account_key)
resjson = response.json()
access_token = resjson["access_token"]

#Some global vars...
NAME = "movie"
COUNTER = 0;
ENCRYPTION = "1" # 0=None, StorageEncrypted=1, CommonEncryptionProtected=2, EnvelopeEncryptionProtected=4
ENCRYPTION_SCHEME = "StorageEncryption" # StorageEncryption or CommonEncryption.
VIDEO_NAME = "movie.mp4"
VIDEO_PATH = "../assets/movie.mp4"
ASSET_FINAL_NAME = "Python Sample-OCR"
PROCESSOR_NAME = "Azure Media OCR"
MODE = "OCR"
OCR_CONFIG = "ocr_config.json"

# Just a simple wrapper function to print the title of each of our phases to the console...
def print_phase_header(message):
        global COUNTER;
        print ("\n[" + str("%02d" % int(COUNTER)) + "] >>> " +  message)
        COUNTER += 1;

# This wrapper function prints our messages to the console with a timestamp...
def print_phase_message(message):
        time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print (str(time_stamp) + ": " +  message)

### get ams redirected url
response = amspy.get_url(access_token)
if (response.status_code == 200):
        ams_redirected_rest_endpoint = str(response.url)
else:
        print_phase_message("GET Status: " + str(response.status_code) + " - Getting Redirected URL ERROR." + str(response.content))
        exit(1)


######################### PHASE 1: UPLOAD #########################
### create an asset
print_phase_header("Creating a Media Asset")
response = amspy.create_media_asset(access_token, NAME)
if (response.status_code == 201):
	resjson = response.json()
	asset_id = str(resjson['d']['Id'])
	print_phase_message("POST Status.............................: " + str(response.status_code))
	print_phase_message("Media Asset Name........................: " + NAME)
	print_phase_message("Media Asset Id..........................: " + asset_id)
else:
	print_phase_message("POST Status.............................: " + str(response.status_code) + " - Media Asset: '" + NAME + "' Creation ERROR." + str(response.content))

### create an assetfile
print_phase_header("Creating a Media Assetfile (for the video file)")
response = amspy.create_media_assetfile(access_token, asset_id, VIDEO_NAME, "false", "false")
if (response.status_code == 201):
	resjson = response.json()
	video_assetfile_id = str(resjson['d']['Id'])
	print_phase_message("POST Status.............................: " + str(response.status_code))
	print_phase_message("Media Assetfile Name....................: " + str(resjson['d']['Name']))
	print_phase_message("Media Assetfile Id......................: " + video_assetfile_id)
	print_phase_message("Media Assetfile IsPrimary...............: " + str(resjson['d']['IsPrimary']))
else:
	print_phase_message("POST Status: " + str(response.status_code) + " - Media Assetfile: '" + VIDEO_NAME + "' Creation ERROR." + str(response.content))