/*eslint no-var: "error" */
/*eslint no-unused-vars: "off" */
/*eslint linebreak-style: "off" */
/*eslint no-trailing-spaces: "off" */
/*eslint no-console: "off" */
/*eslint-env es6*/
// Put this file in path/to/plugin/amd/src
// You can call it anything you like

import {call} from 'core/ajax';
import notification from 'core/notification';

import Vue from './vue/vue';

import RVComponents from './report-viewer-components';
Vue.use(RVComponents);

import TSComponents from './treestudyplan-components';
import Debugger from './util/debugger';

import {ProcessStudyplans} from './studyplan-processor';


import PortalVue from './portal-vue/portal-vue.esm';
Vue.use(PortalVue);
import BootstrapVue from './bootstrap-vue/bootstrap-vue.esm';
Vue.use(BootstrapVue);

let debug = new Debugger("treestudyplan-report");

/**
 * Initialize the Page
 * @param {string} type Type of page to show
 * @param {Object} arg Arguments passed
 */
 export function init(type="myreport",arg) {
    let app = new Vue({
        el: '#root',
        data: {
            "studyplans": [],
        },
        mounted() {
            let call_method;
            let call_args;
            if(type == "invited"){
                call_method = 'local_treestudyplan_get_invited_studyplan';
                call_args = {"invitekey": arg};
            }
            else if(type == "other"){
                call_method = 'local_treestudyplan_get_user_studyplans';
                call_args = {"userid": arg};
            }
            else if(type == "teaching"){
                call_method = 'local_treestudyplan_get_teaching_studyplans';
                call_args = {};
            }
            else{
                call_method = 'local_treestudyplan_get_own_studyplan';
                call_args = {};
            }
            call([{
                methodname: call_method,
                args: call_args
            }])[0].done(function(response){
                debug.info("Studyplans:",response);
                const timingval = { future: 0, present: 1, past: 2, };
                response.sort((a,b) => {
                    const timinga = TSComponents.studyplanTiming(a);
                    const timingb = TSComponents.studyplanTiming(b);

                    let t = timingval[timinga] - timingval[timingb];
                    if(t == 0){
                        // sort by start date if timing is equal
                        t = new Date(b.startdate).getTime() - new Date(a.startdate).getTime();
                        
                        if (t == 0) {
                            // sort by name if timing is equal
                            t = a.name.localeCompare(b.name);
                        }
                    }
                    return t;
                });
                app.studyplans = ProcessStudyplans(response);
            }).fail(notification.exception);            
        
        },

        methods: {
           
        },
    });

}

