#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
# from caostk.plotting.viewvideo import VideoViewer

sys.path.append("analyzer")
from analyzer import Record

# Plotting related stuff:
# from caostk.plotting import virdis, virdis_r

import matplotlib
matplotlib.rcParams['font.family'] = 'serif'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

import colormaps as cmaps

from matplotlib.patches import Wedge
import matplotlib.patheffects as path_effects
import matplotlib.image as mpimg

from matplotlib.patches import FancyArrow

#################################
# Get the data:
r1 = Record(#'/home/shajahan/Research/Experiments/Unpinning'
            '2015-02-13_Exp005_Rec004_CascadeII512.dat',
            102, 102, 0.010, 500, 18500)
r1.apply_default_filter()

# v = VideoViewer(r1.data)
# v.show()

d1 = r1.data[100:]
d2 = r1.data[197:]

r2 = Record(#'/run/user/1000/gvfs/sftp:host=sirona01'
            #'/data.bmp/heart/Users/Shajahan/2015-02-13/'
            '2015-02-13_Exp005_Rec007_CascadeII512.dat',
            102, 102, 0.010, 600, 7500)
r2.apply_default_filter()
d3 = r2.data[486:]

#################################
# Plotting instanciation:
SNAPS = 6
STEPS = 15

fig = plt.figure(figsize=(6, 3.7))
fig.subplots_adjust(left=0.1, right=0.97, top=0.93, bottom=0.12)  # right = 0.97

grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(3, SNAPS),
                 axes_pad=0.05,  # pad between axes in inch.
                 label_mode="L", cbar_size="4%", cbar_pad=0.1,
                 cbar_mode='single', aspect=True, share_all=True,
                 cbar_location='bottom')

vmin = -250
vmax = 700  # 450
cax = grid.cbar_axes[0]

circle_center = (46.25, 50)
circle_radius = 10

outer_center = (50, 48)
outer_radius = 42.5
width = 30
edge = 2

#################################

textx, texty = None, None

for row, data in enumerate((d1, d2, d3)):
    for frame in range(SNAPS):
        ax = grid[row * SNAPS + frame]
        # print(data.shape)

        if row == 0:
            if frame == 0:
                ax.set_title(u"$0$")
            elif frame < SNAPS-1:
                ax.set_title(u"${}$".format(10*frame*STEPS))
            else:
                ax.set_title(u"${} \\rm{{ms}}$".format(10*frame*STEPS))

        img = ax.imshow(data[frame*STEPS], cmap=cmaps.viridis,
                        interpolation='nearest',
                        origin='lower', vmin=vmin, vmax=vmax)

        arrowPatch = FancyArrow(0.985, 0.3, 0.0, 0.45, width=0.01,
               length_includes_head=False,
               head_width=0.02, head_length=0.02,
               shape='full', overhang=0,
               head_starts_at_zero=False,
               transform=ax.figure.transFigure,
               clip_on=False, color="black", linewidth=0.1)

        ax.add_patch(arrowPatch)

        circle = plt.Circle(circle_center, radius=circle_radius,
                            color='w', lw=2.0)
        ax.add_patch(circle)
        outside = Wedge(outer_center, outer_radius+width, 0, 360,
                        width=width, color='w', transform=ax.transData)
        ax.add_patch(outside)
        cx, cy = outer_center
        ax.set_xlim(cx - outer_radius - edge, cx + outer_radius + edge)
        ax.set_ylim(cy - outer_radius - edge, cy + outer_radius + edge)
        lx, ux = cx - outer_radius, cx + outer_radius
        # ax.set_xticks([lx+0.5, ux-0.5])
        ax.set_xticks([])
        ax.set_yticks([])


        # add the wave emitting sites:
        if row == 1 and frame == 1:
            #ax.plot(42, 10, 'r*', ms=11, scalex=False, scaley=False,
            #        mec='none', mew=1)
            t = ax.text(25, 1.5, r'S1', ha='left', va='bottom',
                        fontsize=14, fontdict={'color': 'k'})
            t.set_path_effects(
                [path_effects.Stroke(linewidth=2, foreground='white'),
                 path_effects.Normal()])
        if row == 2 and frame == 1:
            #ax.plot(28, 83, 'r*', ms=11, scalex=False, scaley=False,
            #        mec='none', mew=1)
            t = ax.text(7, 90.5, r'S2', ha='left', va='top',
                        fontsize=14, fontdict={'color': 'k'})
            t.set_path_effects(
                [path_effects.Stroke(linewidth=2, foreground='white'),
                 path_effects.Normal()])

plt.colorbar(img, cax, orientation='horizontal', label='normalized intensity')

# Need to draw for the text placement to work well:
plt.draw()

for row in range(3):
    ax = grid[row * SNAPS]
    t = ['(a)', '(b)', '(c)']
    if row == 0:
        textx, texty = ax.transAxes.inverted().transform(
            fig.transFigure.transform([0, 1]))
    ax.text(textx, 1, t[row], va='center', ha='right',
            transform=ax.transAxes, fontsize=20)

l = ax.text(60, 260, r'R', fontsize=14, fontdict={'color':'k'})
l.set_path_effects(
                [path_effects.Stroke(linewidth=2, foreground='white'),
                 path_effects.Normal()])


ax.text(568, 230, r"\textbf{$E$}", fontsize=14, color="black")

plt.savefig("Fig2.pdf")
