aboutsummaryrefslogtreecommitdiff
path: root/src/Analyze.tsx
blob: e7563d52adab6842d78082e5af3c0a810a4cc920 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import React from 'react';
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import { DateRangePicker, FocusedInputShape } from 'react-dates';
import { Theme, withStyles } from '@material-ui/core/styles';
import cyan from '@material-ui/core/colors/cyan';
import deepOrange from '@material-ui/core/colors/deepOrange';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import FormControl from '@material-ui/core/FormControl';
import FormGroup from '@material-ui/core/FormGroup';
import Grid from '@material-ui/core/Grid';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import IconButton from '@material-ui/core/IconButton';
import moment from 'moment';

import PatternTable from './PatternTable';
import AlertDialog from './Dialog';
import Snackbar, { SnackbarVariant } from './Snackbar';
import * as gapi from './gapi';
import { MsgType, MsgClient } from './msg';
import { Pattern, PatternEntry, PatternEntryFlat } from './pattern';
import { AnalyzePieChart } from './Chart';
import { getGraphData } from './graph';

const defaultChartData = [
    {name: 'Work', value: 10, color: cyan[300]},
    {name: 'Wasted', value: 10, color: deepOrange[300]}];

const styles = (theme: Theme) => ({
    buttonSpacer: {
        marginBottom: theme.spacing.unit * 4,
    },
});

type AnalyzeProps = {
    classes: { buttonSpacer: string }
};

class Analyze extends React.Component<AnalyzeProps> {
    msgClient: MsgClient;
    dialogPromiseResolver: (r: boolean) => void;

    state = {
        patterns: [] as PatternEntry[],
        calendars: {} as { [id: string]: gapi.GCalendarMeta },
        startDate: null as moment.Moment,
        endDate: null as moment.Moment,
        patternGraphData: defaultChartData,
        calendarGraphData: defaultChartData,
        snackBarOpen: false,
        snackBarMsg: 'unknown',
        snackBarVariant: 'error' as SnackbarVariant,
        dialogOpen: false,
        dialogMsg: {title: '', message: ''},
        focusedInput: null as FocusedInputShape
    };

    constructor(props: AnalyzeProps) {
        super(props);

        this.msgClient = new MsgClient('main');

        this.msgClient.sendMsg({
            opt: MsgType.getPatterns,
            data: { id: 'analyze' }
        }).then(msg => {
            this.setState({
                patterns: msg.data.map((p: PatternEntryFlat) => PatternEntry.inflate(p))
            });
        });

        this.msgClient.sendMsg({
            opt: MsgType.getCalendars,
            data: { enabledOnly: true }
        }).then(msg => {
            this.setState({ calendars: msg.data });
        });

        this.msgClient.sendMsg({
            opt: MsgType.getLoggedIn,
            data: {}
        }).then(msg => {
            if (!msg.data)
                this.openSnackbar('Not logged in. Operating in offline mode.',
                                    'warning' as SnackbarVariant);
        });

        this.dialogPromiseResolver = null;
    }

    loadPatterns(patterns: PatternEntry[]) {
        this.msgClient.sendMsg({
            opt: MsgType.updatePatterns,
            data: { id: 'analyze', patterns: patterns.map(p => p.deflate()) }
        }).then(() => this.setState({ patterns }));
    };

    updatePattern = (field: string, idx: number, value: PatternEntry[]) => {
        let patterns = this.state.patterns;
        // hack here
        (patterns[idx] as {[key: string]: any})[field] = value;
        this.loadPatterns(patterns);
    };

    removePattern = (idx: number) => {
        let patterns = this.state.patterns;
        patterns.splice(idx, 1);
        for (let i = 0; i < patterns.length; i++)
            patterns[i].idx = i;
        this.loadPatterns(patterns);
    };

    newPattern = () => {
        let patterns = [PatternEntry.defaultPatternEntry(0), ...this.state.patterns];
        for (let i = 1; i < patterns.length; i++)
            patterns[i].idx = i;
        this.loadPatterns(patterns);
    };

    getCalEvents = async (id: string, start: Date, end: Date): Promise<gapi.GCalendarEvent[]> => {
        let { data } = await this.msgClient.sendMsg({
            opt: MsgType.getCalEvents,
            data: { id,
                    start: start.getTime(),
                    end: end.getTime() }
        });
        return data.map((_e: gapi.GCalendarEventFlat) => (
            gapi.GCalendarEvent.inflate(_e)
        ));
    }

    analyze = async () => {
        if (!(this.state.startDate && this.state.endDate)) {
            this.openSnackbar('Please choose a valid time range.',
                            'error' as SnackbarVariant);
            return;
        }
        let start = this.state.startDate.startOf('day').toDate();
        let end = this.state.endDate.startOf('day').toDate();
        let r = await getGraphData(start, end,
                    this.state.patterns,
                    this.state.calendars,
                    this.getCalEvents);
        this.setState({ patternGraphData: r.patternGraphData,
                        calendarGraphData: r.calendarGraphData });
    }

    reset = async () => {
        let ans = this.openDialog("Reset", "Are you sure to reset the patterns?");
        if (!ans) return;
        this.loadPatterns([]);
        this.setState({ startDate: null, endDate: null });
    }

    loadDefaultPatterns() {
        let patterns = [];
        let idx = 0;
        for (let id in this.state.calendars) {
            let cal = this.state.calendars[id];
            if (!cal.enabled) continue;
            patterns.push(new PatternEntry(cal.name, idx++,
                new Pattern(id, false, cal.name, cal.name),
                Pattern.anyPattern(),
                cal.color));
        }
        this.loadPatterns(patterns);
    }

    loadDefault = async () => {
        let ans = await this.openDialog("Load Default", "Load the calendars as patterns?");
        if (!ans) return;
        this.loadDefaultPatterns();
    }

    openSnackbar(msg: string, variant: SnackbarVariant) {
        this.setState({ snackBarOpen: true, snackBarMsg: msg, snackBarVariant: variant });
    }

    openDialog(title: string, message: string) {
        let pm = new Promise(resolver => {
            this.dialogPromiseResolver = resolver
        });
        this.setState({ dialogOpen: true, dialogMsg: { title, message } });
        return pm;
    }

    handleSnackbarClose = (event: React.SyntheticEvent<{}>, reason: string) => {
        if (reason === 'clickaway') return;
        this.setState({ snackBarOpen: false });
    }

    handleDialogClose = (ans: boolean) => {
        this.dialogPromiseResolver(ans);
        this.setState({ dialogOpen: false });
    }

    render() {
        const { classes } = this.props;

        return (
            <Grid container spacing={16} style={{minWidth: 700}}>
                <AlertDialog
                    title={this.state.dialogMsg.title}
                    message={this.state.dialogMsg.message}
                    open={this.state.dialogOpen}
                    handleClose={this.handleDialogClose}/>
                <Snackbar
                    message={this.state.snackBarMsg}
                    open={this.state.snackBarOpen}
                    variant={this.state.snackBarVariant}
                    onClose={this.handleSnackbarClose}/>
                <Grid item container md={6} xs={12} spacing={16}>
                    <Grid item xs={12}>
                            <Typography variant="h6" component="h1" gutterBottom>
                                Analyzed Events
                                <IconButton
                                    style={{marginBottom: '0.12em', marginLeft: '0.5em'}}
                                    onClick={() => this.newPattern()}><AddCircleIcon /></IconButton>
                            </Typography>
                            <PatternTable
                                patterns={this.state.patterns}
                                calendars={this.state.calendars}
                                onRemovePattern={this.removePattern}
                                onUpdatePattern={this.updatePattern} />
                    </Grid>
                    <Grid item xs={12}>
                            <Typography variant="h6" component="h1" gutterBottom>
                                Time Range
                            </Typography>
                        <FormControl fullWidth={true}>
                        <FormGroup>
                            <div style={{textAlign: 'center'}}>
                                <DateRangePicker
                                    startDate={this.state.startDate}
                                    startDateId="start_date_id"
                                    endDate={this.state.endDate}
                                    endDateId="end_date_id"
                                    onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })}
                                    focusedInput={this.state.focusedInput}
                                    onFocusChange={focusedInput => this.setState({ focusedInput })}
                                    isOutsideRange={() => false} />
                            </div>
                        </FormGroup>
                        <div className={classes.buttonSpacer} />
                        <Grid container spacing={16}>
                            <Grid item lg={4} xs={12}>
                                <FormGroup>
                                    <Button variant="contained" color="primary" onClick={this.loadDefault}>Load Default</Button>
                                </FormGroup>
                            </Grid>
                            <Grid item lg={4} xs={12}>
                                <FormGroup>
                                    <Button variant="contained" color="primary" onClick={this.reset}>Reset</Button>
                                </FormGroup>
                            </Grid>
                            <Grid item lg={4} xs={12}>
                                <FormGroup>
                                    <Button variant="contained" color="primary" onClick={this.analyze}>Analyze</Button>
                                </FormGroup>
                            </Grid>
                        </Grid>
                        </FormControl>
                    </Grid>
                </Grid>
                <Grid item md={6} xs={12}>
                    <Typography variant="h6" component="h1" gutterBottom>
                        Results
                    </Typography>
                    <AnalyzePieChart
                        patternGraphData={this.state.patternGraphData}
                        calendarGraphData={this.state.calendarGraphData}/>
                </Grid>
            </Grid>
        );
    }
}


export default withStyles(styles)(Analyze);