# -*- coding: utf-8 -*-

import os
import csv
import numpy as np

import dirfiles
from confparser import load_config

import expyriment
from expyriment import design, control, stimuli, io, misc


def launch_protocol(protocol_ini, exp, gender, vs):
    # %%
    # ======================== LOAD CONFIG.INI FILE ===========================

    # Select .ini file for instructions
    setting = load_config(protocol_ini)

    # %%
    # ========================== LOAD INPUT FILES =============================

    # Define the pathway of the inputs directory
    inputs_path = os.path.abspath(setting["inputs_dir"] + gender +
                                  '/version_' + vs)
    print inputs_path
    # List input csv files
    inputs_filenames = dirfiles.listdir_csvnohidden(inputs_path)
    inputs_filenames.sort()

    # %%
    # ======== WAITS FOR USER TO ENTER BLOCK (AKA RUN) NUMBER TO START ========

    # Define number of runs
    nb_block = len(inputs_filenames)

    # Wait 5 seconds in order to launch input text screen
    exp.keyboard.wait(duration=5000)

    # Create text input box
    ti = io.TextInput(message='Block number:', message_text_size=24,
                      message_colour=map(int, setting["bcolor"]),
                      user_text_colour=map(int, setting["ucolor"]),
                      ascii_filter=misc.constants.K_ALL_DIGITS,
                      frame_colour=(70, 70, 70))

    # Load user's input
    while True:
        sb = ti.get('0')
        # If string is empty
        if not sb:
            warning_message1 = stimuli.TextLine(setting["wm1"].decode('utf-8'),
                                                text_size=24,
                                                text_colour=(204, 0, 0))
            warning_message1.present()
            exp.keyboard.wait(misc.constants.K_RETURN, duration=5000)
            continue
        # If block number introduced is higher than the number of blocks
        # preset in config file
        elif int(sb) >= nb_block:
            warning_message2 = stimuli.TextLine(setting["wm2"].decode('utf-8'),
                                                text_size=24,
                                                text_colour=(204, 0, 0))
            warning_message2.present()
            exp.keyboard.wait(misc.constants.K_RETURN, duration=5000)
            continue
        else:
            start_block = int(sb)
            break

    # %%
    # ============================== DESIGN ===================================

    # Stimuli sequence of the protocol
    session_list = [[i for i in csv.reader(open(inputs_filename))]
                   for inputs_filename in inputs_filenames]

    # Define the blocks using expyriment module
    block_list = [expyriment.design.Block(name="block%d" % bs)
                  for bs in np.arange(nb_block)]

    # For all blocks in the block list...
    for bl in np.arange(nb_block):
        # ...add stimuli to the trials and add trials to the blocks
        for l,line in enumerate(session_list[bl]):
            # Create a trial
            trial = design.Trial()
            # Retrieve variables from input files at every trial and
            # label them according to what is defined by var_names
            for tsf in np.arange(len(setting["var_names"]) - 1):
                trial.set_factor(setting["var_names"][tsf],
                                 line[tsf].decode('utf-8'))
            trial.set_factor(setting["var_names"][-1],
                             line[-2].decode('utf-8'))
            # Create stimuli...
            if line[1] == '0':
                # ... (1) for Rest trial,
                # (i.e. between encoding and recognition), ...
                if line[0] == '+':
                    fixcross_isi = stimuli.FixCross(size=(30, 30),
                                                    line_width=3,
                                                    colour=(255, 255, 255))
                    # Add fixation cross to the trial
                    trial.add_stimulus(fixcross_isi)
                # (2) for Instructions trial, ...
                else:
                    instruction = stimuli.TextLine(line[4].decode('utf-8'),
                                                   position=(0, 250),
                                                   text_size=56,
                                                   text_colour=(255, 153, 51))