/*
 * Project Name: map-board
 * File Name: thread-show.js
 * Last modified: 2017/11/20 1:16
 * Author: Hiroaki Goto
 *
 * Copyright (c) 2017 Hiroaki Goto. All rights reserved.
 */

var Vue = require('vue');
var io = require('socket.io-client');
var $ = require('jquery');
var axios = require('axios');
let myClient = axios.create({
    xsrfHeaderName: 'X-CSRF-Token',
    withCredentials: true
});
var ws_endpoint = 'https://' + window.location.host;
var thread_id = $('#thread-id').val();
var param = '?id=' + thread_id;
var socket = io.connect(ws_endpoint + param);
socket.on('CREATE', function(data) {
    console.log("CREATE event coming");
    console.log(data);
    id = parseInt(data.id);
    idx = binsearch(vm2.newPosts, id, (post) => parseInt(post.id));
    vm2.newPosts.splice(idx, 0, data);
});
socket.on('EDIT', function(data) {
    console.log("EDIT event coming");
});
socket.on('DELETE', function(data) {
    console.log("DELETE event coming");
    id = parseInt(data.id);
    idx = binsearch(vm2.posts, id, (post) => parseInt(post.id) );
    if(idx < vm2.posts.length && id === parseInt(vm2.posts[idx].id)) {
        vm2.posts.splice(idx, 1);
        return;
    }
    idx = binsearch(vm2.newPosts, id, (post) => parseInt(post.id) );
    if(idx < vm2.newPosts.length && id === parseInt(vm2.newPosts[idx].id)) {
        vm2.newPosts.splice(idx, 1);
        return;
    }
    vm2.deletedPostIds.push(parseInt(id));
});

Vue.component('post-view', require('./components/post-view.vue'));
Vue.component('autosize-textarea', require('./components/autosize-textarea.vue'));
Vue.component('infinite-loader', require('./components/infinite-loader.vue'));
Vue.directive('focus', {
    inserted: function (el) {
        el.focus();
    }
});

function binsearch(array, target, extractor) {
    let ok = 0;
    let ng = array.length;
    while(Math.abs(ok - ng) > 1) {
        let mid = Math.floor((ok + ng) / 2);
        if(target <= extractor(array[mid])) {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    return ok;
}


var vm2 = new Vue({
    el: ".posts-wrapper",
    data: {
        deleteId: -1,
        newPosts: [],
        posts: [],
        deletedPostIds: [],
        myId: "",
        oldestId: "",
        noMorePost: false
    },
    methods: {
        visibleDeleteConfirmation: function(id) {
            this.deleteId = id;
            this.$refs.deleteModal.style.display = "block";
            this.$refs.overlay.style.display = "block";
        },
        closeDeleteConfirmation: function() {
            this.$refs.deleteModal.style.display = "none";
            this.$refs.overlay.style.display = "none";
        },
        addOlderPosts: function(data) {
            if(data.length == 0) {
                this.noMorePost = true;
            }
            this.posts = this.posts.concat(data);
            if(this.posts.length > 0) {
                this.oldestId = this.posts[this.posts.length - 1].id;
            }
        }
    },
    created: function() {
        this.myId = document.getElementsByName('my-id')[0].value;
    }
});

if(document.getElementById('post-form') !== null) {
    var vm = new Vue({
        el: "#post-form",
        props: {
            tokenInfo: require('./components/csrf-token.js')
        },
        data: {
            inputtedContent: '',
            noticeMessage: '',
            lastTimeoutId: null
        },
        methods: {
            postAction: function () {
                this.switchDisable('content', true);
                this.switchDisable('action', true);
                let self = this;
                let data = {
                    id: thread_id,
                    content: this.inputtedContent,
                    [this.tokenInfo.sc_name]: this.tokenInfo.token
                };
                myClient.post('/api/threads/posts/create.php', data
                ).then(function (response) {
                    self.$refs.noticeContent.classList.add('active');
                    self.noticeMessage = "投稿しました";
                    self.switchDisable('content', false);
                    self.switchDisable('action', false);
                    self.inputtedContent = '';
                    if (self.lastTimeoutId != null) {
                        window.clearTimeout(self.lastTimeoutId);
                    }
                    self.lastTimeoutId = window.setTimeout(() => {
                        self.lastTimeoutId = null;
                        self.$refs.noticeContent.classList.remove('active');
                    }, 3000);
                }).catch(function (error) {
                    self.$refs.noticeContent.classList.add('active');
                    self.noticeMessage = "投稿に失敗";
                    if (error.response.status === 403) {
                        self.noticeMessage += "： ログインが必要です";
                    } else {
                        self.noticeMessage += "： 不明なエラーです";
                    }
                    self.switchDisable('content', false);
                    self.switchDisable('action', false);
                    if (self.lastTimeoutId != null) {
                        window.clearTimeout(self.lastTimeoutId);
                    }
                    self.lastTimeoutId = window.setTimeout(() => {
                        self.lastTimeoutId = null;
                        self.$refs.noticeContent.classList.remove('active');
                    }, 3000);
                });
            },
            switchDisable: function (name, disable) {
                for (let elem of document.getElementsByName(name)) {
                    elem.isDisabled = disable;
                }
            }
        },
    });
}