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

import {get_string,get_strings} from 'core/str';
import {call} from 'core/ajax';
import notification from 'core/notification';

import Vue from './vue/vue';


import EditorComponents from './studyplan-editor-components';
Vue.use(EditorComponents);

import TSComponents from './treestudyplan-components';
Vue.use(TSComponents);

import ModalComponents from './modedit-modal';
Vue.use(ModalComponents);
import Debugger from './util/debugger';

import {load_strings} from './util/string-helper';
import {ProcessStudyplan} from './studyplan-processor';
import {download,upload} from './downloader';

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

import {Drag, Drop, DropList} from './vue-easy-dnd/vue-easy-dnd.esm';
Vue.component('drag',Drag);
Vue.component('drop',Drop);
Vue.component('drop-list',DropList);

const debug = new Debugger("treestudyplan");

let strings = load_strings({
    studyplan: {
        studyplan_select_placeholder: 'studyplan_select_placeholder',
    },
});

/**
 * Initialize the Page
 * @param {int} contextid The context we should attempt to work in (1:1 related to the category)
 * @param {int} categoryid The category we shoud attempt to work in (1:1 related to the context)
 */
export function init(contextid,categoryid) {
    // Make sure the id's are numeric and integer
    if(undefined === contextid || !Number.isInteger(Number(contextid)) || contextid < 1 ){ contextid = 1;} 
    else { contextid = Number(contextid);} // ensure a numeric value instead of string
    if(undefined === categoryid || !Number.isInteger(Number(categoryid))){ categoryid = 0;}
    else { categoryid = Number(categoryid);} // ensure a numeric value instead of string

    const in_systemcontext = (contextid <= 1);

    // Setup the initial Vue app for this page
    let app = new Vue({
        el: '#root',
        data: {
            create: {
                studyplan: {
                    name: '',
                    shortname: '',
                    description: '',
                    idnumber: '',
                    slots : 4,
                    startdate: '2020-08-01',
                    enddate: '',
                    context: contextid,
                    aggregation: 'bistate',
                    aggregation_config: '',
                }
            },
            toolbox: {
                right: true,
            },
            activestudyplan: null,
            loadingstudyplan: false,
            studyplans: [],
            frameworks: [],
            badges: [],
            courses: [],
            text: strings.studyplan,
            usedcontexts: [],
        },
        created() {
            this.$root.$on('studyplanRemoved',(studyplan)=>{
                
                if(app.activestudyplan == studyplan){
                    app.activestudyplan = null;
                }

                // remove studyplan from index list
                let index = null;
                for(let idx in app.studyplans){
                    if(app.studyplans[idx].id == studyplan.id){
                        index = idx;
                        break;
                    }
                }
                if(index){
                    app.studyplans.splice(index, 1);
                }

            });
        },
        mounted() {
            call([{
                methodname: 'local_treestudyplan_list_studyplans',
                args: { context_id: contextid}
            }])[0].done(function(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 = response;

                // load studyplan from hash if applicable
                const hash = location.hash.replace('#','');
                if(hash){
                    for(let idx in app.studyplans){
                        if(app.studyplans[idx].id == hash){
                            app.selectStudyplan(app.studyplans[idx]);
                            break;
                        }
                    }
                }
            }).fail(notification.exception);
            call([{
                methodname: 'local_treestudyplan_list_badges',
                args: {}
            }])[0].done(function(response){
                app.badges = response;
            }).fail(notification.exception);          
            call([{
                methodname: 'local_treestudyplan_map_categories',
                args: {root_id: categoryid}
            }])[0].done(function(response){
                app.courses = response;
            }).fail(notification.exception);    
            call([{
                methodname: 'local_treestudyplan_list_used_categories',
                args: { operation: 'edit'}
            }])[0].done(function(response){
                app.usedcontexts = response;
            }).fail(notification.exception);    

        },
        computed: {
            dropdown_title(){
                if(this.activestudyplan && this.activestudyplan.name){
                    return this.activestudyplan.name;
                }
                else{
                    return this.text.studyplan_select_placeholder;
                }
            },
            contextid(){
                return contextid;
            },
            filterComponentType(){
                return {
                    item: false,
                    component: true,
                    span: 1,
                    type: 'filter',
                };
            },
        },
        methods: {
            closeStudyplan() {
                app.activestudyplan = null;
                location.hash = '';
            },         
            movedStudyplan(plan,from,to) {
                // reload the page in the new context (needed, since a number of links are not reactive in the page)
                const params = new URLSearchParams(location.search);
                params.delete('categoryid');
                params.set("contextid", to);
                window.location.search = params.toString();
            },
            onStudyPlanCreated(newstudyplan){
                app.studyplans.push(newstudyplan);
                app.selectStudyplan(newstudyplan);

            },
            switchContext(ctx){
                const params = new URLSearchParams(location.search);
                params.set('categoryid', ctx.id);
                window.location.search = params.toString();
                
            },
            selectStudyplan(studyplan){
                // fetch studyplan
                app.loadingstudyplan = true;
                app.activestudyplan = null;
                call([{
                    methodname: 'local_treestudyplan_get_studyplan_map',
                    args: { id: studyplan.id}
                }])[0].done(function(response){
                    app.activestudyplan = ProcessStudyplan(response,true);
                    debug.info('studyplan processed');
                    app.loadingstudyplan = false;
                    location.hash = app.activestudyplan.id;
                }).fail(function(error){
                    notification.exception(error);
                    app.loadingstudyplan = false;
                });
            },
            import_studyplan(){
                upload((filename,content)=>{
                    call([{
                        methodname: 'local_treestudyplan_import_plan',
                        args: {
                            content: content,
                            format: "application/json",
                            context_id: contextid,
                        },
                    }])[0].done(function(response){
                        if(response.success){
                            location.reload();
                        } else {
                            debug.error("Import failed: ",response.msg);
                        }
                        
                    }).fail(notification.exception);  
                }, "application/json");
            },
            export_plan(plan,format){
                let self = this;
                if(format == undefined || !["json","csv"].includes(format)){
                    format = "json";
                }
                call([{
                        methodname: 'local_treestudyplan_export_plan',
                        args: {
                            studyplan_id: plan.id,
                            format: format
                        },
                    }])[0].done(function(response){
                        
                        download(plan.shortname+".json",response.content,response.format);
                    }).fail(notification.exception);    
            },
        },
    });
}

