try:
    WindowsError
except NameError:
    WindowsError = None

try:
    FileNotFoundError
except NameError:
    FileNotFoundError = None

try:
    OSError
except NameError:
    OSError = None

import pytest

pytestmark = pytest.mark.django_db

from bs4 import BeautifulSoup
import re
from parameterized import parameterized
from django.test import TestCase, Client,override_settings, RequestFactory, TransactionTestCase

from django.core.management import call_command
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils.six import StringIO
from django.test.client import RequestFactory
from rowers.views import c2_open, multi_compare_view


from rowers.forms import (
    DocumentsForm,CNsummaryForm,RegistrationFormUniqueEmail,
    ChartParamChoiceForm,WorkoutMultipleCompareForm,
    BoxPlotChoiceForm)
import rowers.plots as plots
import rowers.interactiveplots as iplots
import datetime
from rowingdata import rowingdata as rdata
from rowingdata import rower as rrower
from django.utils import timezone
from rowers.rows import handle_uploaded_file
from django.core.files.uploadedfile import SimpleUploadedFile
from time import strftime,strptime,mktime,time,daylight
import os
from rowers.tasks import handle_makeplot
from rowers.utils import serialize_list,deserialize_list
from rowers.utils import NoTokenError
from rowers.plannedsessions import get_dates_timeperiod
from shutil import copyfile, copy
from nose.tools import assert_true
from mock import Mock, patch
#from minimocktest import MockTestCase
import pandas as pd
import rowers.c2stuff as c2stuff

from django.urls import reverse, reverse_lazy

import json
import numpy as np

from rowers import urls
from rowers.views import (
    error500_view,error404_view,error400_view,error403_view
    )

from rowers.dataprep import delete_strokedata
from django.contrib.sessions.middleware import SessionMiddleware

from django.conf import settings
from importlib import import_module

from redis import StrictRedis
redis_connection = StrictRedis()

from django_mailbox.models import Mailbox,MessageAttachment,Message

from rowers.tests.mocks import *

from nose.tools import assert_raises

from rowers.models import *
from rowers.forms import *
from rowers.tests.mocks import *
import factory
from faker import Factory
from uuid import uuid4
faker = Factory.create()

from rowers.utils import calculate_age

from rowers.tasks import handle_getagegrouprecords
from rowers.opaque import encoder

import inspect

def get_random_file(filename='rowers/tests/testdata/testdata.csv',name=''):

    frm = inspect.stack()[3]
    mod = inspect.getmodule(frm[0])
    try:
        fromstring = 'test_%s_' % mod.__name__
    except AttributeError:
        fromstring = 'none_'

    row = rdata(filename)
    totaldist = row.df['cum_dist'].max()
    totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
    totaltime = totaltime+row.df.loc[row.df.index[0],' ElapsedTime (sec)']


    hours = int(totaltime/3600.)

    minutes = int((totaltime - 3600.*hours)/60.)
    seconds = int(totaltime - 3600.*hours - 60.*minutes)
    tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

    duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)
    duration = datetime.time(hour=hours,minute=minutes,second=seconds)

    workoutdate = row.rowdatetime.date()
    workoutstarttime = row.rowdatetime

    extension = filename[-3:]

    if name != '':
        newfilename = 'rowers/tests/testdata/temp/'+fromstring+name+'.'+extension
    else:
        newfilename = 'rowers/tests/testdata/temp/'+fromstring+uuid4().hex[:16]+'.'+extension

    # copyfile(filename,newfilename)
    copy(filename,newfilename)

    thedict = {
        'row':row,
        'filename':newfilename,
        'startdatetime': row.rowdatetime,
        'starttime': workoutstarttime,
        'date': workoutdate,
        'duration':duration,
        'totaldist':totaldist,
        }

    return thedict

class UserFactory(factory.DjangoModelFactory):
    class Meta:
        model = User
        django_get_or_create = ('username',)

    email = factory.LazyAttribute(lambda _: faker.email())
    username = factory.LazyAttribute(lambda _: faker.profile()['username'])

    first_name = factory.LazyAttribute(lambda _:faker.name().split(' ')[0])
    last_name = factory.LazyAttribute(lambda _:faker.name().split(' ')[0])

class RaceFactory(factory.DjangoModelFactory):
    class Meta:
        model = VirtualRace

    name = factory.LazyAttribute(lambda _: faker.word())
    registration_closure = timezone.now()+datetime.timedelta(days=1)
    evaluation_closure = timezone.now()+datetime.timedelta(days=2)
    startdate = timezone.now().date()
    start_time = datetime.time()
    enddate = (timezone.now()+datetime.timedelta(days=1)).date()
    end_time = datetime.time()
    preferreddate = timezone.now().date()
    sessiontype = 'indoorrace'
    sessionvalue = 1
    sessionmode = 'time'

class WorkoutFactory(factory.DjangoModelFactory):
    class Meta:
        model = Workout

    name = factory.LazyAttribute(lambda _: faker.word())
    notes = faker.text()
    startdatetime = get_random_file(name=faker.word())['startdatetime']
    starttime = get_random_file(name=faker.word())['starttime']
    workouttype='water'
    date=timezone.now().date()
    duration=get_random_file(name=faker.word())['duration']
    distance=get_random_file(name=faker.word())['totaldist']
    csvfilename=get_random_file(name=faker.word())['filename']


class SessionFactory(factory.DjangoModelFactory):
    class Meta:
        model = PlannedSession

    name = factory.LazyAttribute(lambda _: faker.word())
    comment = faker.text()

@pytest.fixture(scope="session", autouse=True)
def cleanup(request):
    def remove_test_files():
        try:
            for filename in os.listdir('media/mailbox_attachments'):
                path = os.path.join('media/mailbox_attachments/',filename)
                if not os.path.isdir(path):
                    try:
                        os.remove(path)
                    except OSError:
                        pass
        except OSError:
            pass

        try:
            for filename in os.listdir('rowers/tests/testdata/temp'):
                path = os.path.join('rowers/tests/testdata/temp/',filename)
                if not os.path.isdir(path):
                    try:
                        os.remove(path)
                    except OSError:
                        pass
        except OSError:
            pass




    request.addfinalizer(remove_test_files)
