aboutsummaryrefslogtreecommitdiff
path: root/src/Settings.tsx
blob: c6e5a00af169bc28cdf51edb5a0eff5a2685eb56 (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import React from 'react';
import classNames from 'classnames';
import { Theme, withStyles, StyleRules } from '@material-ui/core/styles';
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 RefreshIcon from '@material-ui/icons/Refresh';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import IconButton from '@material-ui/core/IconButton';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Checkbox from '@material-ui/core/Checkbox';
import TextField from '@material-ui/core/TextField';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';

import PatternTable from './PatternTable';
import Snackbar, { SnackbarVariant } from './Snackbar';
import AlertDialog from './Dialog';
import * as gapi from './gapi';
import { MsgType, MsgClient } from './msg';
import { Pattern, PatternEntry, PatternEntryFlat } from './pattern';
import { DurationFlat, TrackedPeriodFlat } from './duration';

const styles = (theme: Theme): StyleRules => ({
    tableHead: {
        verticalAlign: 'top',
        textAlign: 'right',
        lineHeight: '3em',
    },
    tableContent: {
        textAlign: 'left',
        maxWidth: 600,
    },
    calendarList: {
        maxHeight: 400,
        overflowY: 'auto'
    },
    bottomButtons: {
        marginTop: 10,
        textAlign: 'right'
    },
    trackedPeriodInput: {
        paddingTop: 10,
        paddingBottom: 10
    }
});

const STableCell = withStyles(theme => ({
    body: {
        fontSize: 16,
    },
}))(TableCell);

const CompactListItem = withStyles(theme => ({
    dense: {
        paddingTop: 0,
        paddingBottom: 0
    },
}))(ListItem);

type TrackedPeriodInputProps = {
    name: string
    fromDuration: DurationFlat,
    toDuration: DurationFlat,
    nameOnChange: (name: string) => void,
    fromOnChange: (d: DurationFlat) => void,
    toOnChange: (d: DurationFlat) => void
};

class TrackedPeriodInput extends React.Component<TrackedPeriodInputProps> {
    valueOnChange = (old: DurationFlat, onChange: (d: DurationFlat) => void) => (
        (event: React.ChangeEvent<HTMLSelectElement>) => {
            onChange({ value: event.target.value, unit: old.unit});
        }
    );

    unitOnChange = (old: DurationFlat, onChange: (d: DurationFlat) => void) => (
        (event: React.ChangeEvent<HTMLSelectElement>) => {
            onChange({ value: old.value, unit: event.target.value});
        }
    );

    static styles = {
        periodName: {
            textAlign: 'right'
        },
        periodValue: {
            width: 30,
            textAlign: 'center'
        }
    };

    static toValue(value: any) {
        if (isNaN(value)) return null;
        let v = parseInt(value, 10);
        if (v < 0 || v > 999) return null;
        return v;
    }

    render() {
        let {
            fromDuration, toDuration,
            nameOnChange, name,
            fromOnChange, toOnChange
        } = this.props;

        let units = [
            <MenuItem key='days' value='days'>Day(s)</MenuItem>,
            <MenuItem key='weeks' value='weeks'>Week(s)</MenuItem>,
            <MenuItem key='months' value='months'>Month(s)</MenuItem>
        ];

        return (
            <span>
                <TextField
                    inputProps={{ style: TrackedPeriodInput.styles.periodName } as React.CSSProperties}
                    value={name}
                    onChange={event => nameOnChange(event.target.value)}/>:
                from <TextField
                    error={TrackedPeriodInput.toValue(fromDuration.value) === null}
                    inputProps={{ style: TrackedPeriodInput.styles.periodValue } as React.CSSProperties}
                    value={fromDuration.value}
                    onChange={this.valueOnChange(fromDuration, fromOnChange)} />
                <Select value={fromDuration.unit}
                    onChange={this.unitOnChange(fromDuration, fromOnChange)}>{units}</Select> ago
                to <TextField
                    error={TrackedPeriodInput.toValue(toDuration.value) === null}
                    inputProps={{style: TrackedPeriodInput.styles.periodValue} as React.CSSProperties}
                    value={toDuration.value}
                    onChange={this.valueOnChange(toDuration, toOnChange)} />
                <Select value={toDuration.unit}
                    onChange={this.unitOnChange(toDuration, toOnChange)}>{units}</Select> ago
            </span>
        );
    }
}

type SettingsProps = {
    classes: {
        tableHead: string,
        tableContent: string,
        calendarList: string,
        bottomButtons: string,
        trackedPeriodInput: string
    }
};

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

    state = {
        isLoggedIn: false,
        patterns: [] as PatternEntry[],
        calendars: {} as {[id: string]: gapi.GCalendarMeta},
        config: {} as { trackedPeriods: TrackedPeriodFlat[] },
        snackBarOpen: false,
        snackBarMsg: 'unknown',
        snackBarVariant: 'error' as SnackbarVariant,
        dialogOpen: false,
        dialogMsg: {title: '', message: ''},
        calendarsLoading: false,
    };

    constructor(props: SettingsProps) {
        super(props);
        gapi.getLoggedIn().then(b => this.setState({ isLoggedIn: b }));

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

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

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

        this.msgClient.sendMsg({
            opt: MsgType.getConfig,
            data: ['trackedPeriods']
        }).then(msg => {
            let config = {
                trackedPeriods: msg.data.trackedPeriods
            };
            console.log(msg.data.trackedPeriods);
            this.setState({ config });
        });

        this.dialogPromiseResolver = null;
    }

    handleLogin = async () => {
        try {
            await gapi.login();
            this.setState({ isLoggedIn: true });
            this.loadAll(true);
        } catch (_) {
            this.openSnackbar("Failed to login!", 'error' as SnackbarVariant);
        }
    }

    handleLogout = async () => {
        let ans = await this.openDialog("Logout", "Are you sure to logout?");
        if (!ans) return;
        try {
            await gapi.logout();
            this.setState({ isLoggedIn: false });
        } catch (_) {
            this.openSnackbar("Failed to logout!", 'error' as SnackbarVariant);
        }
    }

    toggleCalendar(id: string) {
        var calendars = {...this.state.calendars};
        calendars[id].enabled = !calendars[id].enabled;
        this.setState({ calendars });
    }

    async loadAll(reloadAll = false) {
        await new Promise(resolver => (this.setState({ calendarsLoading: true }, resolver)));

        let pm_colors = gapi.getAuthToken().then(gapi.getColors).then(color => color.calendar);
        let pm_cals = gapi.getAuthToken().then(gapi.getCalendars);
        let [colors, _cals] = await Promise.all([pm_colors, pm_cals]);
        var cals: { [id: string]: gapi.GCalendarMeta } = {};
        _cals.forEach((cal: any) => {
            cals[cal.id] = {
                name: cal.summary,
                color: colors[cal.colorId],
                enabled: true
            };
        });

        let pms = [this.loadCalendars(cals, reloadAll)];
        if (reloadAll)
            pms.push(this.loadDefaultPatterns(cals));
        await Promise.all(pms);
        this.setState({ calendarsLoading: false });
    };

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

    loadCalendars(calendars: {[ id: string ]: gapi.GCalendarMeta }, enabled = false) {
        if (!enabled)
            for (let id in this.state.calendars) {
                if (calendars.hasOwnProperty(id))
                    calendars[id].enabled = this.state.calendars[id].enabled;
            }
        this.setState({ calendars });
    }

    loadPatterns(patterns: PatternEntry[], id: string) {
        this.setState({ patterns });
    }

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

    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, 'main');
    };

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

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

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

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

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

    updateTrackedPeriods = (trackedPeriods: TrackedPeriodFlat[]) => {
        this.setState({...this.state.config, trackedPeriods });
    }

    handlePeriodNameChange = (idx: number) => (name: string) => {
        let trackedPeriods = [...this.state.config.trackedPeriods];
        trackedPeriods[idx].name = name;
        this.updateTrackedPeriods(trackedPeriods);
    }

    handlePeriodFromChange = (idx: number) => (duration: DurationFlat) => {
        let trackedPeriods = [...this.state.config.trackedPeriods];
        trackedPeriods[idx].start = duration;
        this.updateTrackedPeriods(trackedPeriods);
    }

    handlePeriodToChange = (idx: number) => (duration: DurationFlat) => {
        let trackedPeriods = [...this.state.config.trackedPeriods];
        trackedPeriods[idx].end = duration;
        this.updateTrackedPeriods(trackedPeriods);
    }

    handleApply = async () => {
        let trackedPeriods = this.state.config.trackedPeriods;
        if (trackedPeriods.some(p => (
                TrackedPeriodInput.toValue(p.start.value) === null ||
                TrackedPeriodInput.toValue(p.end.value) === null ))) {
            this.openSnackbar("Invalid time range!", 'error' as SnackbarVariant);
            return;
        }

        let pm1 = this.msgClient.sendMsg({
            opt: MsgType.updateCalendars,
            data: this.state.calendars
        });
        let pm2 = this.msgClient.sendMsg({
            opt: MsgType.updatePatterns,
            data: { id: 'main', patterns: this.state.patterns.map(p => p.deflate()) }
        });
        let pm3 = this.msgClient.sendMsg({
            opt: MsgType.updateConfig,
            data: { trackedPeriods }
        });
        await Promise.all([pm1, pm2, pm3]);
        this.openSnackbar("Saved changes.", 'success' as SnackbarVariant);
    }

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

    render() {
        const { classes } = this.props;
        return (
            <div>
                <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}/>
               <Typography variant="h6" component="h1" gutterBottom>
                   General
               </Typography>
               <Table>
                   <TableBody>
                       <TableRow>
                           <STableCell className={classes.tableHead}>Account</STableCell>
                           <STableCell className={classes.tableContent}>
                               {
                                   (this.state.isLoggedIn &&
                                       <Button variant="contained" color="primary" onClick={this.handleLogout}>Logout</Button>) ||
                                       <Button variant="contained" color="primary" onClick={this.handleLogin}>Login</Button>
                               }
                           </STableCell>
                       </TableRow>
                       <TableRow>
                           <STableCell className={classes.tableHead}>
                           <IconButton
                               style={{marginBottom: '0.12em', marginRight: '0.5em'}}
                               onClick={() => this.loadAll(false)}
                               disabled={this.state.calendarsLoading || !this.state.isLoggedIn}>
                               <RefreshIcon />
                           </IconButton>
                               Calendars
                           </STableCell>
                           <STableCell className={classes.tableContent}>
                               {(this.state.isLoggedIn &&
                               <List className={classes.calendarList}>
                                   {Object.keys(this.state.calendars).sort().map(id =>
                                       <CompactListItem
                                           key={id}
                                           onClick={() => this.toggleCalendar(id)}
                                           disableGutters
                                           dense button >
                                       <Checkbox
                                           checked={this.state.calendars[id].enabled}
                                           disableRipple />
                                       <ListItemText primary={this.state.calendars[id].name} />
                                       </CompactListItem>)}
                               </List>) || 'Please Login.'}
                           </STableCell>
                       </TableRow>
                       <TableRow>
                           <STableCell className={classes.tableHead}>
                               <IconButton
                                   style={{marginBottom: '0.12em', marginRight: '0.5em'}}
                                   onClick={() => this.newPattern()}
                                   disabled={!this.state.isLoggedIn}><AddCircleIcon /></IconButton>
                               Tracked Events
                               <div>
                               <Button
                                   variant="contained"
                                   color="primary"
                                   onClick={this.handleLoadDefault}>Load Default</Button>
                               </div>
                           </STableCell>
                           <STableCell className={classes.tableContent}>
                               {(this.state.isLoggedIn &&
                               <FormControl fullWidth={true}>
                               <PatternTable
                                   patterns={this.state.patterns}
                                   calendars={this.state.calendars}
                                   onRemovePattern={this.removePattern}
                                   onUpdatePattern={this.updatePattern} />
                               </FormControl>) || 'Please Login.'}
                           </STableCell>
                       </TableRow>
                       <TableRow>
                           <STableCell className={classes.tableHead}>
                                Tracked Time Range
                           </STableCell>
                           <STableCell className={classNames(classes.tableContent, classes.trackedPeriodInput)}>
                               {this.state.config.trackedPeriods &&
                                   this.state.config.trackedPeriods.map((p, idx) =>
                                   <FormGroup key={idx}>
                                   <TrackedPeriodInput
                                       name={p.name}
                                       fromDuration={p.start}
                                       toDuration={p.end}
                                       nameOnChange={this.handlePeriodNameChange(idx)}
                                       fromOnChange={this.handlePeriodFromChange(idx)}
                                       toOnChange={this.handlePeriodToChange(idx)}/>
                                   </FormGroup>)}
                           </STableCell>
                       </TableRow>
                   </TableBody>
               </Table>
               <div className={classes.bottomButtons}>
               <Button
                    variant="contained"
                    color="primary"
                    onClick={this.handleApply}>Apply</Button>
                </div>
            </div>
        );
    }
}

export default withStyles(styles)(Settings);