daddy.controller("forumCtrlr", function($scope, $http, $location) {

    $scope.titles = {
        main : "Talking Points...",
        list : "Catergories",
        last : "Last Topic"
    }

    $scope.errors = {
        topic : {
            show : false,
            text : "None yet!"
        },
        catagory : {
            show : false,
            text: "None yet!"
        }
    }

    $scope.getCategories = () => {
        console.log("getting categories form server")
        $http({
            url : server + "/forum/category/all",
            method : "GET"
        }).then((res) => {
            if (res.status == 200) {
                if (res.data.length == 0) {
                    $scope.errors.catagory.show = true
                } else {
                    $scope.categories = res.data
                    for (let i = 0; i < res.data.length; i++) {
                        $http({
                            url : server + "/forum/category/topic/last?cat=" + res.data[i].catNo,
                            method : "GET"
                        }).then((res) => {
                            if (res.status == 200) {
                                console.log("topicNo: " + res.data.topicNo)
                                // if (res.data.topicNo == null) {
                                //     $scope.errors.topic.show = true
                                // } else {
                                    res.data.topicDate = niceDate(res.data.topicDate)
                                    $scope.categories[i].lastTopic = res.data
                                // }
                            } else {
                                console.log("server has encountered an error: " + res.status)
                            }
                        })
                    }
                    console.log(res)
                }
            }
        }).catch((res) => {
            console.log("server has encountered an error: " + res.status)
        })
    }

    $scope.setCat = (catNo) => {
        $location.path("/forum/category/"+catNo)
    }

    $scope.setTopic = (topicNo) => {
        $location.path("/forum/topic/"+topicNo)
    }

})

daddy.controller("createTopicCtrlr", function($scope, $location, $http, stateData) {

    $scope.titles = {
        form : "Create a topic!"
    }

    $scope.status = {
        show : false,
        text : ""
    }

    let error = {
        loggedIn : {
            show : false,
            text1 : "You must be",
            link1 : "Logged In",
            text2 : "to create a topic!"
        },
        userLevel : {
            show : false,
            text1 : "No categories have been created, please contact an administrator about creating some.",
            text2 : "Administrator contact: solomonlaing@inkletblot.com"
        },
        category : {
            show : false
        }
    }
    
    $scope.error = error

    $scope.start = () => {
        if (stateData.state.user.userName == null) {
            console.log("not logged in.")
            error.loggedIn.show = true
        }
        if (stateData.state.user.userLevel == 0) {
            console.log("user not an admin.")
            error.userLevel.show = true
        }
        $scope.getCategories()
    }

    $scope.getCategories = () => {
        console.log("getting categories form server")
        $http({
            url : server + "/forum/category/all",
            method : "GET"
        }).then((res) => {
            if (res.status == 200) {
                if (res.data.length == 0) {
                    $scope.errors.catagory.show = true
                } else {
                    $scope.categories = res.data                
                    console.log(res)
                }
            }
        }).catch((res) => {
            console.log("server has encountered an error: " + res.status)
        })
    }

    $scope.setLogin = () => {
        $location.path("/login")
        stateData.setPage("things")
    }

    $scope.createTopic = () => {
        console.log("sending new topic to server!!")
        let formData = new FormData()
        formData.append('topicSubject', $scope.topic.topicSubject)
        formData.append('topicCat', $scope.topic.topicCat)
        formData.append('userNo', stateData.state.user.userNo)
        $http({
            url : server + "/forum/topic/create",
            method : "POST",
            data : formData,
            headers : { 'Content-Type' : undefined },
            transformRequest : angular.identity
        }).then((res) => {
            if (res.status == 200) {
                console.log("topic submitted")
                $scope.createPost($scope.topic.postContent, res.data.topicNo)
            }
        }).catch((res) => {
            if (res.status == 500) {
                console.log("something went wrong: " + res.data)
                $scope.status.text = "Something went wrong: " + res.status
            }
        })
    }

    $scope.createPost = (postContent, topicNo) => {
        console.log("sending new post to server")
        let formData = new FormData()
        formData.append('postContent', postContent)
        formData.append('topicNo', topicNo)
        formData.append('userNo', stateData.state.user.userNo)
        $http({
            url : server + "/forum/topic/post/create",
            method : "POST",
            data : formData,
            headers : { 'Content-Type' : undefined },
            transformRequest : angular.identity
        }).then((res) => {
            if (res.status == 200) {
                console.log("post added")
                $location.path("/forum/topic/" + topicNo)
            }
        }).catch((res) => {
            if (res.status == 500) {
                console.log("something went wrong: " + res.data)
                $scope.status.text = "Something went wrong: " + res.status
            }
        })
    }
})

daddy.controller("createCategoryCtrlr", function($scope, $http, $location, stateData) {

    let error = {
        loggedIn : {
            show : false,
            text1 : "You must be",
            link1 : "Logged In",
            text2 : "to create a category!"
        },
        userLevel : {
            show : false,
            text1 : "You must be an administrator to create a category!"
        }
    }

    $scope.error = error

    $scope.titles = {
        form : "Create a Category!"
    }

    $scope.status = {
        show : false,
        text : ""
    }

    $scope.start = () => {
        if (stateData.state.user.userName == null) {
            error.loggedIn.show = true
        }
        if (stateData.state.user.userLevel == 0) {
            error.userLevel.show = true
        }
    }

    $scope.setLogin = () => {
        $location.path("/login")
        stateData.setPage("things")
    }

    $scope.createCategory = () => {
        $scope.status.show = true
        $scope.status.text = "Adding category..."

        let formData = new FormData()
        formData.append('catName', $scope.category.catName)
        formData.append('catDescr', $scope.category.catDescr)

        console.log("sending to server...")
        $http({
            url : server + "/forum/category/create",
            method : "POST",
            data : formData,
            headers : { 'Content-Type' : undefined },
            transformRequest : angular.identity
        }).then((res) => {
            if (res.status == 200) {
                console.log("category submitted")
                $location.path("/forum/category/" + res.data.catNo)
            }
        }).catch((res) => {
            if (res.status == 500) {
                console.log("something went wrong: " + res.data)
                $scope.status.text = "Something went wrong: " + res.status
            }
        })
    }

})

daddy.controller("topicCtrlr", function($scope, $routeParams, $timeout, $http, $location, stateData) {
    stateData.setPage("forum")

    $scope.error = false
    $scope.message = {
        start : null,
        link : "Go Back!"
    }
    $scope.logged = {
        text1 : "You must be",
        link1 : "logged in",
        text2 : "to reply. You can also",
        link2 : "sign up",
        text3 : "for an account."
    }
    $scope.status = {
        show : false,
        text : "",
    }
    $scope.first = {
        show : false,
        text : "Be the first to create a post, write below..."
    }

    $scope.getTopic = () => {
        console.log("getting topic")
        $http({
            url : server + "/forum/topic?topic=" + $routeParams.topicNo,
            method : "GET"
        }).then((res) => {
            if (res.status == 200) {
                let topic = res.data
                // if (res.data.posts.length == 0) {
                //     $scope.first.show = true
                // }

                for (let i = 0; i < topic.posts.length; i++) {
                    topic.posts[i].postDate = niceDate(topic.posts[i].postDate)
                }
                $scope.topic = topic
            }
        }).catch((res) => {
            if (res.status == 404) {
                console.log(res.data)
                $scope.error = true
                $scope.message.start = "No such topic,"
            } else if (res.status == 500) {
                console.log(res.data)
                $scope.error = true
                $scope.message.start = "An error has occured: " + res.status
            } else {
                console.log(res)
            }
        })
    }

    $scope.makeReply = (topicNo) => {
        console.log("sending new post to server")
        let formData = new FormData()
        formData.append('postContent', $scope.reply.postContent)
        formData.append('topicNo', topicNo)
        formData.append('userNo', stateData.state.user.userNo)
        $http({
            url : server + "/forum/topic/post/create",
            method : "POST",
            data : formData,
            headers : { 'Content-Type' : undefined },
            transformRequest : angular.identity
        }).then((res) => {
            if (res.status == 200) {
                console.log("post added")
                $scope.reply.postContent = ""                
                $timeout(function() { $scope.getTopic() }, 2000)
            }
        }).catch((res) => {
            if (res.status == 500) {
                console.log("something went wrong: ")
                console.log(res.data)
                $scope.status.text = "Something went wrong: " + res.status
            }
        })
    }

    $scope.setLogin = () => {
        $location.path("/login")
    }

    $scope.setSignup = () => {
        $location.path("/signup")
    }

    $scope.deletePost = (postNo) => {
        if (!window.confirm("Are you sure you want to delete this post?")) {
            return
        }
        $http({
            url : server + "/forum/topic/post/delete?postNo=" + postNo,
            method : "POST"
        }).then((res) => {
            if (res.status == 200) {
                console.log("post deleted")
                for (let i = 0; i < $scope.topic.posts.length; i++) {
                    if ($scope.topic.posts[i].postNo == postNo) {
                        $scope.topic.posts[i].postContent = "[deleted]"
                    }
                }
            }
        }).catch((res) => {
            if (res.status == 500) {
                console.log("something went wrong: ")
                console.log(res.data)
                $scope.status.text = "Something went wrong: " + res.status
            }
        })
    }

    $scope.editPost = (postNo, postContent) => {
        /* This is incomplete, need to figure out hiding the edit box after edit. Would rather not use timeout. */
        console.log("submitting edited post")
        let formData = new FormData()
        formData.append("postNo", postNo)
        formData.append("postContent", postContent)
        $http({
            url : server + "/forum/topic/post/edit",
            method : "POST",
            data : formData,
            headers : { 'Content-Type' : undefined },
            transformRequest : angular.identity
        }).then((res) => {
            if (res.status == 200) {
                console.log("post edited")
                for (let i = 0; i < $scope.topic.posts.length; i++) {
                    if ($scope.topic.posts[i].postNo == postNo) {
                        $scope.topic.posts[i].postContent = postContent + " [edited]"
                    }
                }
            }
        }).catch((res) => {
            if (res.status == 500) {
                console.log("something went wrong: ")
                console.log(res.data)
                $scope.status.text = "Something went wrong: " + res.status
            }
        })
    }

})

daddy.controller("categoryCtrlr", function($scope, $http, $routeParams, $location, stateData) {
    stateData.setPage("forum")

    $scope.errors = {
        exists : {
            show : false,
            text1 : "No such category,",
            link1 : "Go Back!"
        },
        empty : {
            show : false,
            text : "No topics have been created yet..."
        }
    }

    $scope.titles = {
        topic : "topic",
        date : "date"
    }

    $scope.getCat = () => {
        console.log("getting category")
        $http({
            url : server + "/forum/category?cat=" + $routeParams.catNo,
            method : "GET"
        }).then((res) => {
            console.log(res)
            if (res.status == 200) {
                let category = res.data
                if (category.topics.length == 0) {
                    $scope.errors.empty.show = true
                } else {
                    for (let i = 0; i < category.topics.length; i++) {
                        category.topics[i].topicDate = niceDate(category.topics[i].topicDate)
                    }
                }
                $scope.category = category
            }
        }).catch((res) => {
            if (res.status == 404) {
                console.log(res.data)
                $scope.errors.exists.show = true
            } else if (res.status == 500) {
                console.log(res.data)
            } else {
                console.log(res)
            }
        })
    }

    $scope.setTopic = (topicNo) => {
        $location.path("/forum/topic/"+topicNo)
    }
    
    $scope.setForum = () => {
        $location.path("/forum")
    }
})

niceDate = (string) => {
    let date = new Date(string)
    return "on " + date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " at " + date.getHours() + ":" + date.getMinutes()
}

isNum = (str) => {
    let re = /^[0-9]+$/
    return re.test(String(str).toLowerCase())
}