Controllers.prototype.manageProximitySegment = (function () {
    return newSegment;

    function newSegment(core, e, data, returnCB, segID) {
        return new Segment(core, e, data, returnCB, segID);
    }

    function Segment(core, e, data, returnCB, segID) {
        var em = new EventManager(),
            dm = null,
            container = null,
            save = null;

        if (!!segID) {
            apiRequest("GET", "segments/proximity/byKey", segID, null, init);
        } else {
            init(null);
        }

        this.exit = exit;

        function init(inbound) {
            container = document.createElement("div");
            container.classList.add("manageProximity");
            returnCB();
            e.appendChild(container);
            dm = DrawMap.New({
                "radiusThresholds": [
                    {
                        "value": 0,
                        "label": "0m"
                    },
                    {
                        "value": 1000,
                        "label": "10m"

                    },
                    {
                        "value": 2200,
                        "label": "20m"
                    },
                    {
                        "value": 9600,
                        "label": "50m"
                    }
                ]
            }, container, !!inbound && !!inbound.data ? inbound.data : null, insertItems);
        }

        function insertItems() {
            var saveContainer = document.createElement("save-container");
            save = newSaveButton(e);
            saveContainer.appendChild(save);
            container.appendChild(saveContainer);
            em.add(save, "click", saveAction);
        }

        function saveAction(e) {
            preventDefault(e);
            if (!!segID) {
                apiRequest('PUT', 'segments/proximity/byKey', segID, dm.getSegment(), responseAction);
            } else {
                apiRequest('POST', 'segments/proximity/byKey', core.userID, dm.getSegment(), responseAction);
            }
        }

        function responseAction(e, s) {
            if (s === 200) {
                core.notifications.setSuccess("Successfully saved proximity segment! (ID: " + e.data + ")");
            } else {
                core.notifications.setErrors(e.errors)
                return
            }

            dm.exit();
            pop("Pop!", "Segments", "/dashboard/segments");
        }

        function exit() {
            dm.exit();
            removeChild(e, container);
            em.reset();
        }
    }

    function newSaveButton() {
        var btn = document.createElement("a");
        btn.setAttribute("class", "button mint");
        btn.textContent = "Save";
        return btn;
    }
})();