<script>
    var sort_data = function (objects, sort) {
        if(sort == 'desc'){
            return objects.sort(function(a, b) {
                a = moment(a.start_date);
                b = moment(b.start_date);
                return a>b ? -1 : a<b ? 1 : 0;
            });
        } else if(sort == "asc"){
            return objects.sort(function(a,b){return moment(a.start_date) - moment(b.start_date)});
        }
    }
    var generate_search_terms = function(projects){
        var terms = [];
        projects.forEach(project => {
            terms.push({ text: project.title, type: 'project', classes : 'result-project' });
            var date = moment(new Date(project.date)).format('YYYY');
            terms.push({ text: date, type: 'year', classes : 'result-date' });
            project.tags.forEach(tag => {
                terms.push({ text: tag, type: 'tag', classes : 'result-tag' });
            })
            project.contacts.forEach(contact => {
                terms.push({text: contact.name, type: 'contact', classes : 'result-contact'});
            })
        });
        var filtered_terms = [];
        terms.forEach(term => {
            var found = false;
            for (let i = 0; i < filtered_terms.length; i++) {
                if(term.text == filtered_terms[i].text) found = true;
            }
            if(found == false) filtered_terms.push(term);
        });
        return filtered_terms;
    }

    var app = new Vue({
        el: '#vue-app',
        data: {
            view : {
                type: 'cards',
                sort : 'desc'
            },
            contactMessage : {
                name: "",
                email: "",
                content: ""
            },
            contactMessageSuccess : false,
            contactMessageError : false,
            projects : sort_data(projectsList, 'desc'),
            search_query : '',
            search_tags : [],
            autocompleteSearchTerms: generate_search_terms(projectsList)
        },
        methods: {
            filterProjects: function(){
                console.log('Filtering projects')
            },
            getDate: function(date){
                return moment(new Date(date)).fromNow();
            },
            getSearchTagIcon: function(category){
                switch (category) {
                    case 'contact':
                        return 'fa-user';
                    case 'tag':
                        return 'fa-tag';
                    case 'project':
                        return 'fa-folder';
                    case 'year':
                        return 'fa-calendar';
                    default:
                        return '';
                }
            },
            sendMessage: function(contactMessage){
                if(contactMessage.name != "" && contactMessage.email != "" && contactMessage.content != ""){
                    console.log("sending message");
                    var req = new XMLHttpRequest();
                    req.overrideMimeType("application/json");
                    req.open('POST', "https://bj2npxevi6.execute-api.us-east-1.amazonaws.com/prod/jamesperet-lambda-mailer", true);
                    req.onload  = function() {
                        var res = req.responseText;
                        console.log(res)
                        if(req.status != 200) app.contactMessageError = true;
                        else app.contactMessageSuccess = true;
                    };
                    req.send(JSON.stringify(contactMessage));
                }
            },
            resetContactForm: function(){
                if(app.contactMessageError == true) app.contactMessageError = false;
                else{
                    app.contactMessageSuccess = false;
                    app.contactMessage.content = ""
                }
            }
        },
        computed: {
            filterSearchTerms() {
                if(this.search_query.length == 1) return [];
                return this.autocompleteSearchTerms.filter(i => {
                    return i.text.toLowerCase().indexOf(this.search_query.toLowerCase()) !== -1;
                });
            },
            filteredProjects(){
                var result = [];
                if(this.search_tags.length == 0){
                    return this.projects;
                } else {
                    console.log(this.search_tags);
                    var filtered = [];
                    this.projects.forEach(project => {
                        filtered.push(project);
                    })
                    this.search_tags.forEach(search_tag => {
                        search = search_tag.text.toLowerCase();
                        if(search_tag.type == 'project'){
                            filtered = filtered.filter(project => {
                                title = project.title.toLowerCase();
                                if(title.includes(search) || title == search ){
                                    return true
                                } 
                            }); 
                        } else if(search_tag.type == 'tag') {
                            console.log("search is tag")
                            filtered = filtered.filter(project => {
                                for (let i = 0; i < project.tags.length; i++) {
                                    const tag = project.tags[i];
                                    if(tag == search) return true;
                                }
                            })
                        } else if(search_tag.type == 'contact') {
                            console.log("search is contact")
                            filtered = filtered.filter(project => {
                                for (let i = 0; i < project.contacts.length; i++) {
                                    var contact = project.contacts[i].name.toLowerCase();
                                    if(contact == search) return true;
                                }
                            })
                        } else if(search_tag.type == 'date') {
                            console.log("search is date")
                            filtered = filtered.filter(project => {
                                if(moment(new Date(project.date)).format('YYYY') == search) return true
                            })
                        } else {
                            filtered = filtered.filter(project => {
                                title = project.title.toLowerCase();
                                if(title.includes(search) || title == search ){
                                    return true
                                }
                                for (let i = 0; i < project.tags.length; i++) {
                                    const tag = project.tags[i];
                                    if(tag.includes(search) || tag == search) {
                                        return true;
                                    }
                                }
                                for (let i = 0; i < project.contacts.length; i++) {
                                    var contact = project.contacts[i].name.toLowerCase();
                                    if(contact.includes(search) || contact == search) {
                                        return true;
                                    }
                                }
                                if(moment(new Date(project.date)).format('YYYY') == search) return true
                                if(project.description.includes(search)){
                                    return true
                                } 
                                return false;
                            })
                        }
                    });
                    return filtered;
                }
            }
        },
        mounted: function () {
            this.$nextTick(function () {
                // Code that will run only after the
                // entire view has been rendered
                if(app.projects.length > 0) console.log(app.projects);
            })
        }
        
    })
</script>