import GapReport from 'trc-client-core/src/report/GapReport';
import GapReportChart from 'trc-client-core/src/report/GapReportChart';
import PrintChartView from 'trc-client-core/src/report/PrintChartView';

import Permissions from 'trc-client-core/src/user/Permissions';
import React from 'react';
import {connect} from 'react-redux';
import {learningPlanCsvUrl} from 'trc-client-core/src/constants/url';

var GapReportViewGeneric = React.createClass({
    displayName: 'GapReportViewGeneric',
    statics: {
        willTransitionTo: function (transition, params) {
            var abort;
            switch(params.pathwayId) {
                case 'tech':
                    abort = !Permissions.get('GAPREPORT_TECHNICAL');
                    break;
                case 'toy_for_life_plan':
                    abort = !Permissions.get('GAPREPORT_TFL');
                    break;
            }

            if(abort) {
                transition.redirect('/unauthorized');
            }
        }
    },
    
    render() {
        var {location, params} = this.props;
        if(Permissions.isPermission('REPORT_VISIBILITY_REGIONAL') && (!location.query.dealerCode)) {
            return null;
        }

        var printChartView = this.renderPrintChartView();

        return (
            <div>
                <GapReportChart
                    view={params.gapReportView || 'grid'}
                    learningPlanId={params.pathwayId}
                    query={location.query}
                    location={location}
                    {...location.query}
                />
                {printChartView}
            </div>
        );
    },

    renderPrintChartView() {
        if(this.props.fetching) {
            return null;
        }

        if(!this.props.lastQuery) {
            // no query specified: we don't know what params to use to fetch the download, hide the download button
            return (
                <PrintChartView />
            );
        }

        if(this.props.lastQuery && this.props.lastQuery.region) {
            // TEMPORARY: export doesn't work yet for regions (12th May 2016), hide download and display message
            return (
                <div>
                    <PrintChartView />
                    <p>This report is too large to export, please contact <a href="mailto:glenn.vanoosterom@blueflag.com.au">Glenn van Oosterom</a> if you require this report as a CSV download.</p>
                </div>
            );
        }

        return (
            <PrintChartView href={learningPlanCsvUrl({
                learningPlanId: this.props.learningPlanId,
                query: this.props.lastQuery
            })}/>
        );
    }
});

export default connect(
    (state) => {
        return {
            lastQuery:  state.gapReport.get('lastQuery'),
            fetching:  state.gapReport.get('fetching')
        }
    }
)(GapReportViewGeneric);