
import tensorflow as tf
print('Using Tensorflow '+tf.__version__)
import matplotlib.pyplot as plt
import sys
# sys.path.append('../')
import os
import csv
import cv2
import numpy as np
from PIL import Image
import time
import math

import src.siamese as siam
from src.visualization import show_frame, show_crops, show_scores


# gpu_device = 2
# os.environ['CUDA_VISIBLE_DEVICES'] = '{}'.format(gpu_device)

# read default parameters and override with custom ones
def tracker(graph, scfg, hp, run, design, frame_name_list, pos_x, pos_y, target_w, target_h, final_score_sz, filename, image, templates_z, scores, label, ownerProb, color, sFrame, eFrame, finalImages, sourceAngle, ):
    num_frames = np.size(frame_name_list)
    if(num_frames < eFrame):
        eFrame = num_frames
    if(len(finalImages) == 0):
        newVector = True
    else:
        newVector = False
    # stores tracker's output for evaluation
    bboxes = np.zeros((num_frames,4))
    val = eFrame-sFrame
    print(val)
    scale_factors = hp.scale_step**np.linspace(-np.ceil(hp.scale_num/2), np.ceil(hp.scale_num/2), hp.scale_num)
    # cosine window to penalize large displacements    
    hann_1d = np.expand_dims(np.hanning(final_score_sz), axis=0)
    penalty = np.transpose(hann_1d) * hann_1d
    penalty = penalty / np.sum(penalty)

    context = design.context*(target_w+target_h)
    z_sz = np.sqrt(np.prod((target_w+context)*(target_h+context)))
    x_sz = float(design.search_sz) / design.exemplar_sz * z_sz

    # thresholds to saturate patches shrinking/growing
    min_z = hp.scale_min * z_sz
    max_z = hp.scale_max * z_sz
    min_x = hp.scale_min * x_sz
    max_x = hp.scale_max * x_sz

    # run_metadata = tf.RunMetadata()
    # run_opts = {
    #     'options': tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
    #     'run_metadata': run_metadata,
    # }

    run_opts = {}

    # with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    with tf.Session(graph=graph) as sess:
        tf.global_variables_initializer().run()
        # Coordinate the loading of image files.
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        
        # save first frame position (from ground-truth)
        bboxes[0,:] = pos_x-target_w/2, pos_y-target_h/2, target_w, target_h                

        image_, templates_z_ = sess.run([image, templates_z], feed_dict={
                                                                        scfg.pos_x_ph: pos_x,
                                                                        scfg.pos_y_ph: pos_y,
                                                                        scfg.z_sz_ph: z_sz,
                                                                        scfg.x_sz0_ph: 0,
                                                                        scfg.x_sz1_ph: 0,
                                                                        scfg.x_sz2_ph: 0,
                                                                        filename: frame_name_list[0]})
        new_templates_z_ = templates_z_

        t_start = time.time()

        
        # Get an image from the queue
        counter = 0.0
        toolbar_width = 40
        for i in range(sFrame, eFrame):
            sys.stdout.write("[")
            sys.stdout.write("*"*int(float(counter/(eFrame-sFrame))*toolbar_width))
            sys.stdout.write(" "*int((1-counter/(eFrame-sFrame))*toolbar_width))
            sys.stdout.write("]")
            sys.stdout.write("%d/%d"%(counter, (eFrame-sFrame)))     
            counter = counter + 1.0
            scaled_exemplar = z_sz * scale_factors
            scaled_search_area = x_sz * scale_factors
            scaled_target_w = target_w * scale_factors
            scaled_target_h = target_h * scale_factors
            image_, scores_ = sess.run(
                [image, scores],
                feed_dict={
                    scfg.pos_x_ph: pos_x,
                    scfg.pos_y_ph: pos_y,
                    scfg.x_sz0_ph: scaled_search_area[0],
                    scfg.x_sz1_ph: scaled_search_area[1],
                    scfg.x_sz2_ph: scaled_search_area[2],
                    templates_z: np.squeeze(templates_z_),
                    filename: frame_name_list[i],
                }, **run_opts)
            scores_ = np.squeeze(scores_)
            # penalize change of scale
            scores_[0,:,:] = hp.scale_penalty*scores_[0,:,:]
            scores_[2,:,:] = hp.scale_penalty*scores_[2,:,:]
            # find scale with highest peak (after penalty)
            new_scale_id = np.argmax(np.amax(scores_, axis=(1,2)))
            # update scaled sizes
            x_sz = (1-hp.scale_lr)*x_sz + hp.scale_lr*scaled_search_area[new_scale_id]        
            target_w = (1-hp.scale_lr)*target_w + hp.scale_lr*scaled_target_w[new_scale_id]
            target_h = (1-hp.scale_lr)*target_h + hp.scale_lr*scaled_target_h[new_scale_id]
            # select response with new_scale_id
            score_ = scores_[new_scale_id,:,:]
            score_ = score_ - np.min(score_)
            score_ = score_/np.sum(score_)
            # apply displacement penalty
            score_ = (1-hp.window_influence)*score_ + hp.window_influence*penalty
            pos_x, pos_y = _update_target_position(pos_x, pos_y, score_, final_score_sz, design.tot_stride, design.search_sz, hp.response_up, x_sz)
            # convert <cx,cy,w,h> to <x,y,w,h> and save output
            bboxes[i,:] = pos_x-target_w/2, pos_y-target_h/2, target_w, target_h
            # update the target representation with a rolling average
            if hp.z_lr>0:
                new_templates_z_ = sess.run([templates_z], feed_dict={
                                                                scfg.pos_x_ph: pos_x,
                                                                scfg.pos_y_ph: pos_y,
                                                                scfg.z_sz_ph: z_sz,
                                                                image: image_
                                                                })

                templates_z_=(1-hp.z_lr)*np.asarray(templates_z_) + hp.z_lr*np.asarray(new_templates_z_)
            
            # update template patch size
            z_sz = (1-hp.scale_lr)*z_sz + hp.scale_lr*scaled_exemplar[new_scale_id]
            
            if run.visualization:
                if(newVector):
                    singleFrame = cv2.imread(frame_name_list[i],1)
                else:
                    singleFrame = finalImages[i-sFrame]
                cv2.rectangle(singleFrame,
                    (int(bboxes[i,0]),int(bboxes[i,1])),
                    (int(bboxes[i,0]+bboxes[i,2]),int(bboxes[i,1]+bboxes[i,3])),
                    color,2)
                #if(color == (0,255,0)):
                #    ownerProb =  .68 + .32 / 2
                #elif(color == (0,0,255)):
                #    ownerProb = .32 / 2
                #cv2.putText(singleFrame,'P('+label+')='+str(ownerProb),(int(bboxes[i,0]),int(bboxes[i,1])),cv2.FONT_HERSHEY_SIMPLEX,0.5, color,2)
                if(newVector):
                    finalImages.append(singleFrame)
                #video.write(singleFrame)
                #show_frame(image_, bboxes[i,:], 1)  
            sys.stdout.write("\b" * int(toolbar_width+5+min(1,counter/10)+min(1,counter/100)+min(1,counter/1000)+min(1,(eFrame-sFrame)/10)+min(1,(eFrame-sFrame)/100)+min(1,(eFrame-sFrame)/1000)))       

        sys.stdout.write("\n")
        t_elapsed = time.time() - t_start
        speed = num_frames/t_elapsed

        # Finish off the filename queue coordinator.
        coord.request_stop()
        coord.join(threads) 

        # from tensorflow.python.client import timeline
        # trace = timeline.Timeline(step_stats=run_metadata.step_stats)
        # trace_file = open('timeline-search.ctf.json', 'w')
        # trace_file.write(trace.generate_chrome_trace_format())

    plt.close('all')
    cv2.destroyAllWindows()
    #video.release()
    return bboxes, speed, finalImages


def _update_target_position(pos_x, pos_y, score, final_score_sz, tot_stride, search_sz, response_up, x_sz):
    # find location of score maximizer
    p = np.asarray(np.unravel_index(np.argmax(score), np.shape(score)))
    # displacement from the center in search area final representation ...
    center = float(final_score_sz - 1) / 2
    disp_in_area = p - center
    # displacement from the center in instance crop
    disp_in_xcrop = disp_in_area * float(tot_stride) / response_up
    # displacement from the center in instance crop (in frame coordinates)
    disp_in_frame = disp_in_xcrop *  x_sz / search_sz
    # *position* within frame in frame coordinates
    pos_y, pos_x = pos_y + disp_in_frame[0], pos_x + disp_in_frame[1]
    return pos_x, pos_y


