import format from 'date-fns/format';
import { upperFirst } from 'lodash';
import * as React from 'react';
import { Subscription } from 'rxjs';
import { BarChart } from '../components/d3/BarChart';
import { FilteredConnection } from '../components/FilteredConnection';
import { PageTitle } from '../components/PageTitle';
import { RadioButtons } from '../components/RadioButtons';
import { Timestamp } from '../components/time/Timestamp';
import { eventLogger } from '../tracking/eventLogger';
import { fetchSiteAnalytics, fetchUserAnalytics } from './backend';
const chartGeneratorOptions = {
    daus: { label: 'Daily unique users', dateFormat: 'E, MMM d' },
    waus: { label: 'Weekly unique users', dateFormat: 'E, MMM d' },
    maus: { label: 'Monthly unique users', dateFormat: 'MMMM YYYY' },
};
const CHART_ID_KEY = 'latest-analytics-chart-id';
class UserActivityHeader extends React.PureComponent {
    render() {
        return (React.createElement("thead", null,
            React.createElement("tr", null,
                React.createElement("th", null, "User"),
                React.createElement("th", null, "Page views"),
                React.createElement("th", null, "Search queries"),
                React.createElement("th", null, "Code intelligence actions"),
                React.createElement("th", { className: "site-admin-analytics-page__date-column" }, "Last active"),
                React.createElement("th", { className: "site-admin-analytics-page__date-column" }, "Last active in code host or code review"))));
    }
}
class UserActivityFooter extends React.PureComponent {
    render() {
        return (React.createElement("tfoot", null,
            React.createElement("tr", null,
                React.createElement("th", null, "Total"),
                React.createElement("td", null, this.props.nodes.reduce((c, v) => c + (v.activity ? v.activity.pageViews : 0), 0)),
                React.createElement("td", null, this.props.nodes.reduce((c, v) => c + (v.activity ? v.activity.searchQueries : 0), 0)),
                React.createElement("td", null, this.props.nodes.reduce((c, v) => c + (v.activity ? v.activity.codeIntelligenceActions : 0), 0)),
                React.createElement("td", { className: "site-admin-analytics-page__date-column" }),
                React.createElement("td", { className: "site-admin-analytics-page__date-column" }))));
    }
}
class UserActivityNode extends React.PureComponent {
    render() {
        return (React.createElement("tr", null,
            React.createElement("td", null, this.props.node.username),
            React.createElement("td", null, this.props.node.activity ? this.props.node.activity.pageViews : 'n/a'),
            React.createElement("td", null, this.props.node.activity ? this.props.node.activity.searchQueries : 'n/a'),
            React.createElement("td", null, this.props.node.activity ? this.props.node.activity.codeIntelligenceActions : 'n/a'),
            React.createElement("td", { className: "site-admin-analytics-page__date-column" }, this.props.node.activity && this.props.node.activity.lastActiveTime ? (React.createElement(Timestamp, { date: this.props.node.activity.lastActiveTime })) : ('n/a')),
            React.createElement("td", { className: "site-admin-analytics-page__date-column" }, this.props.node.activity && this.props.node.activity.lastActiveCodeHostIntegrationTime ? (React.createElement(Timestamp, { date: this.props.node.activity.lastActiveCodeHostIntegrationTime })) : ('n/a'))));
    }
}
class FilteredUserConnection extends FilteredConnection {
}
export const USER_ACTIVITY_FILTERS = [
    {
        label: 'All users',
        id: 'all',
        tooltip: 'Show all users',
        args: { activePeriod: "ALL_TIME" /* ALL_TIME */ },
    },
    {
        label: 'Active today',
        id: 'today',
        tooltip: 'Show users active since this morning at 00:00 UTC',
        args: { activePeriod: "TODAY" /* TODAY */ },
    },
    {
        label: 'Active this week',
        id: 'week',
        tooltip: 'Show users active since Monday at 00:00 UTC',
        args: { activePeriod: "THIS_WEEK" /* THIS_WEEK */ },
    },
    {
        label: 'Active this month',
        id: 'month',
        tooltip: 'Show users active since the first day of the month at 00:00 UTC',
        args: { activePeriod: "THIS_MONTH" /* THIS_MONTH */ },
    },
];
/**
 * A page displaying usage analytics for the site.
 */
export class SiteAdminAnalyticsPage extends React.Component {
    constructor() {
        super(...arguments);
        this.state = {
            chartID: this.loadLatestChartFromStorage(),
        };
        this.subscriptions = new Subscription();
        this.onChartIndexChange = (e) => {
            switch (e.target.value) {
                case 'daus':
                    eventLogger.log('DAUsChartSelected');
                    break;
                case 'waus':
                    eventLogger.log('WAUsChartSelected');
                    break;
                case 'maus':
                    eventLogger.log('MAUsChartSelected');
                    break;
            }
            this.setState({ chartID: e.target.value });
        };
    }
    loadLatestChartFromStorage() {
        const latest = localStorage.getItem(CHART_ID_KEY);
        return latest && latest in chartGeneratorOptions ? latest : 'daus';
    }
    componentDidMount() {
        eventLogger.logViewEvent('SiteAdminAnalytics');
        this.subscriptions.add(fetchSiteAnalytics().subscribe(siteActivity => this.setState({ siteActivity }), error => this.setState({ error })));
    }
    componentDidUpdate() {
        localStorage.setItem(CHART_ID_KEY, this.state.chartID);
    }
    componentWillUnmount() {
        this.subscriptions.unsubscribe();
    }
    render() {
        const chart = chartGeneratorOptions[this.state.chartID];
        return (React.createElement("div", { className: "site-admin-analytics-page" },
            React.createElement(PageTitle, { title: "Analytics - Admin" }),
            React.createElement("h2", null, "Analytics"),
            this.state.error && React.createElement("p", { className: "alert alert-danger" }, upperFirst(this.state.error.message)),
            this.state.siteActivity && (React.createElement(React.Fragment, null,
                React.createElement(RadioButtons, { nodes: Object.entries(chartGeneratorOptions).map(([key, opt]) => ({
                        label: opt.label,
                        id: key,
                    })), onChange: this.onChartIndexChange, selected: this.state.chartID }),
                React.createElement(React.Fragment, null,
                    React.createElement("h3", null, chart.label),
                    React.createElement(BarChart, { showLabels: true, showLegend: true, width: 500, height: 200, isLightTheme: this.props.isLightTheme, data: this.state.siteActivity[this.state.chartID].map(p => ({
                            xLabel: format(Date.parse(p.startTime) + 1000 * 60 * 60 * 24, chart.dateFormat),
                            yValues: {
                                Registered: p.registeredUserCount,
                                Anonymous: p.anonymousUserCount,
                            },
                        })) }),
                    React.createElement("small", { className: "site-admin-analytics-page__tz-note" },
                        React.createElement("i", null, "GMT/UTC time"))))),
            React.createElement("h3", { className: "mt-4" }, "All registered users"),
            !this.state.error && (React.createElement(FilteredUserConnection, { listComponent: "table", className: "table", hideSearch: false, filters: USER_ACTIVITY_FILTERS, noShowMore: false, noun: "user", pluralNoun: "users", queryConnection: fetchUserAnalytics, nodeComponent: UserActivityNode, headComponent: UserActivityHeader, footComponent: UserActivityFooter, history: this.props.history, location: this.props.location }))));
    }
}
//# sourceMappingURL=SiteAdminAnalyticsPage.js.map