import m from 'mithril';
import { catarse, commonAnalytics } from '../api';
import _ from 'underscore';
import h from '../h';
import models from '../models';
import projectInsights from '../c/project-insights';
import projectInsightsSub from '../c/project-insights-sub';

const insights = {
    controller(args) {
        const filtersVM = catarse.filtersVM({
                project_id: 'eq'
            }),
            projectDetails = m.prop([]),
            subscribersDetails = m.prop([]),
            loader = catarse.loaderWithToken,
            setProjectId = () => {
                try {
                    const project_id = m.route.param('project_id');

                    filtersVM.project_id(project_id);
                } catch (e) {
                    filtersVM.project_id(args.root.getAttribute('data-id'));
                }
            };

        setProjectId();
        const l = loader(models.projectDetail.getRowOptions(filtersVM.parameters()));

        l.load().then((data) => {
            projectDetails(data);
            const l2 = commonAnalytics.loaderWithToken(models.projectSubscribersInfo.postOptions({
                id: _.first(data).common_id
            }));
            l2.load().then(subscribersDetails);
        });
        return {
            l,
            filtersVM,
            subscribersDetails,
            projectDetails
        };
    },
    view(ctrl, args) {
        const project = _.first(ctrl.projectDetails()) || {
                user: {
                    name: 'Realizador'
                }
            },
            subscribersDetails = _.first(ctrl.subscribersDetails()) || {
                amount_paid_for_valid_period: 0,
                total_subscriptions: 0,
                total_subscribers: 0
            };

        if (!ctrl.l()) {
            project.user.name = project.user.name || 'Realizador';
        }

        return m('.project-insights', !ctrl.l() ? (
            project.mode === 'sub' ?
            m(projectInsightsSub, {
                args,
                subscribersDetails,
                project,
                l: ctrl.l,
                filtersVM: ctrl.filtersVM
            }) :
            m(projectInsights, {
                args,
                project,
                l: ctrl.l,
                filtersVM: ctrl.filtersVM
            })
        ) : h.loader());
    }
};

export default insights;

@@ -475,34 +475,32 @@
 etails = m.prop(
-%5B%5D
 ),%0A            l
@@ -1596,24 +1596,16 @@
 tails = 
-_.first(
 ctrl.sub
@@ -1613,33 +1613,32 @@
 cribersDetails()
-)
  %7C%7C %7B%0A          

fix subscribers details