# -*- coding: utf-8 -*-
"""
Created on Wed Jun 16 13:03:03 2021

@author: -
"""

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

os.chdir('D:\AcA Mike Dijkhof\Scripts') # set path to folder of formules.py

import formules
    
rootdir = 'D:\AcA Mike Dijkhof\cwa files\Pt204_csv\Pt204_csv35694_0000020406.resampled' # provide path to .csv files of the cut weekdays 
d = {}

for subdir, dirs, files in os.walk(rootdir):
    print(subdir)
    for file in files:
        print(file)
        os.chdir(subdir)
        
        d[file] = pd.read_csv(file, infer_datetime_format=True)

Keys = d.keys()

#%%

Check = formules.SlopeWeeker(Keys, d)
Worklist = Check
Length = pd.DataFrame(np.zeros(((1,int(len(Check)/7)))))

# Create PtName, this depends on subdir string so has to be changed for each patient
PtName = subdir.replace('35694_00000', '')
PtName = PtName.replace('D:\AcA Mike Dijkhof\cwa files\Pt204_csv\Pt204_','') 
PtName = PtName.replace('resampled-','')
PtName = PtName.replace('.resampled','')
PtName = PtName.replace('.csv','')

for i in Length:
   
    CheckWeek = Worklist[:7]
   
    Worklist = Worklist.drop(CheckWeek.index, axis=0)
   
    CheckWeek.loc['Mean','a'] = CheckWeek['a'].median()
    CheckWeek.loc['Mean','b'] = CheckWeek['b'].median()
    CheckWeek.loc['Mean','c'] = CheckWeek['c'].median()
    
    CheckWeek.to_csv('Formula_Week6.csv')
   
    Xscale = np.arange(0,CheckWeek['ENMOmax'].max(), 5)
   
    plt.figure()
    plt.ylim(0,1440)
    plt.xlim(0,CheckWeek['ENMOmax'].max())
    plt.title('All weekdays and average plotted ' + PtName)
    plt.xlabel('Movement intensity [bins of 5 mg]')
    plt.ylabel('Amount of time spend at intensity [min]')
    plt.grid()
   
    for i, r in CheckWeek.iterrows():
        Y = formules.func(Xscale, CheckWeek.loc[i,'a'],CheckWeek.loc[i,'b'], CheckWeek.loc[i,'c'] )
        if i != 'Mean':
            plt.plot(Xscale, Y, 'grey')
        else:
            plt.plot(Xscale, Y, 'k--')
            
    plt.show()
    plt.savefig(fname=('Weekplot ' + PtName+ '.png'))