/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/

/*global $, app */

app.rfcaseEdit = (function () {
    'use strict';
    //---------------- BEGIN MODULE SCOPE VARIABLES --------------
    var
        stateMap = {},
        onSave, onDelete,
        configModule, initModule, onAttachment, onUpload, onAppend;
    //----------------- END MODULE SCOPE VARIABLES ---------------


    //------------------- BEGIN EVENT HANDLERS -------------------

    //ONSAVE
    //
    onSave = function (event) {
        event.preventDefault();
        $.gevent.publish('app-clear-error');

        //get form data
        var formData = $("form").serializeArray({
            checkboxesAsBools: true
        });

        var submitData = app.utilB.objectifyFormDataArray(formData);

        //is this a new record?
        if (stateMap.id != 'new') {
            //put id into the form data
            submitData.id = stateMap.id;


            app.api.update('rfcase', submitData, function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error', res.msg);
                }
            });
        } else {
            //it's a new record - create

            //set dtCreated as it's not a form field
            submitData.dtCreated = app.utilB.getCurrentDateTimeAsEpoch();

            app.api.create('rfcase', submitData, function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error', res.msg);
                } else {
                    page('#!/rfcaseEdit/' + res.id);
                }
            });
        }
        return false; //prevent default?
    };

    //ONDELETE
    //
    onDelete = function (event) {
        event.preventDefault();
        $.gevent.publish('app-clear-error');

        var r = confirm("Are you sure you want to delete this record?");
        if (r == true) {
            //Delete 
            app.api.remove('rfCase/' + stateMap.id, function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error', res.msg);
                } else {
                    //deleted, return to  list
                    page('#!/rfcases');
                    return false;
                }
            });

        } else {
            return false;
        }
        return false; //prevent default?
    };



    ////////////////////////////////////////////
    //Handle click on attachment
    //
    onAttachment = function (event) {
        event.preventDefault();

        var attachmentId = event.data;
        alert("STUB: Attachment click id = " + attachmentId);
        app.api.get('rfcase/' + stateMap.id, function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error', res.msg);
            } else {
                ;
            }
        });

        return false;
    };




    ////////////////////////////////////////////
    //Handle upload click
    //
    onUpload = function (event) {
        event.preventDefault();
        $.gevent.publish('app-clear-error');

        var fileUpload = $("#files").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }

        app.api.uploadFile('rfcaseblob/upload?rfcaseid=' + stateMap.id, fileData, function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error', res.msg);
            } else {
                page('#!/rfcaseEdit/' + stateMap.id);
            }
        });



        return false;
    };

    ////////////////////////////////////
    //ONAPPEND
    // Append date and time and a horizontal line to make a new entry
    //
    onAppend = function (event) {
        event.preventDefault();
        var $notes = $('#notes');
        var txt = $notes.val();
        txt += "\r\n====================\r\n";
        txt += moment().format('MMM Do YYYY H:mm A');//"Aug 28th 2017 11:01 AM"
        txt += ' Edited by ' + app.shell.stateMap.user.name;
        txt += '\r\n\r\n';

        $notes.focus()
            .val("")
            .val(txt);

        return false; //prevent default?
    };

    //-------------------- END EVENT HANDLERS --------------------

    //------------------- BEGIN PUBLIC METHODS -------------------


    //CONFIGMODULE
    //
    configModule = function (context) {
        stateMap.context = context.context;
        if (stateMap.context.params.id) {
            stateMap.id = stateMap.context.params.id;
        }
    };

    //INITMODULE
    //
    initModule = function ($container) {
        if (typeof $container === 'undefined') {
            $container = $('#app-shell-main-content');
        }

        $container.html(Handlebars.templates['app.rfcaseEdit']({}));

        ////app.nav.setContextTitle("Case");

        var $cbProjects = $('#rfCaseProjectId');
        var projectList = {};

        //get projects
        app.api.get('rfcaseproject', function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error', res.msg);
            } else {

                var html = '';

                for (var i = 0, len = res.length; i < len; ++i) {
                    html += ('<option value="' + res[i]['id'] + '">' + res[i]['name'] + '</option>');
                    projectList[res[i]['id']] = res[i]['name'];
                }
                $cbProjects.append(html);

                //Context menu           
                app.nav.contextClear();
                app.nav.contextAddLink("rfcases/", "Cases", "bug");
                app.nav.contextAddLink("rfcaseEdit/new", "New", "plus");
                app.nav.contextAddButton('btn-save-top', 'Save', '', onSave);

                //#####
                //Now load the case itself
                //------------
                //id should always have a value, either a record id or the keyword 'new' for making a new object
                if (stateMap.id != 'new') {
                    //case 3513 (ironically I can't see it yet)
                    document.title = 'Case ' + stateMap.id;
                    //fetch existing record
                    app.api.get('rfcase/' + stateMap.id, function (res) {
                        if (res.error) {
                            $.gevent.publish('app-show-error', res.msg);
                        } else {

                            //set the caseid header //<span class="badge badge-secondary">New</span>
                            $('#caseid').html(stateMap.id);
                            $('#dtcreated').html('created ' + app.utilB.epochToLocalShortDateTime(res.dtCreated));
                            //fill out form
                            app.utilB.formData(res);

                            //Get attachments separately
                            //===============

                            app.api.get('rfcase/' + stateMap.id + '/attachments', function (attachments) {
                                if (attachments.error) {
                                    $.gevent.publish('app-show-error', attachments.msg);
                                } else {

                                    //Create a list item for each attachment
                                    var alist = '';
                                    for (var x = 0; x < attachments.attach.length; x++) {
                                        var attachment = attachments.attach[x];
                                        alist += '<a target="_blank" href="/api/rfcaseblob/download/' + attachment.id + '?dlkey=' + attachments.dlkey + '" class="btn btn-default list-group-item list-group-item-action">' + attachment.name + '</a>'
                                    }

                                    $('#attachments').html(alist);
                                }
                            });

                            //================
                        }
                    });
                    

                    $('#btn-upload').bind('click', onUpload);
                    $('#frmUpload').removeClass('invisible');

                } else {
                    $('#btn-delete').hide();
                    //select rockfish as the default project
                    $cbProjects.val(44);
                    //3 is the default new item priority
                    $('#priority').val(3);

                    //case 3513
                    document.title = 'NEW CASE';
                }
                //-------------
                //#####
            }
        });


        // bind actions      
        $('#btn-save').bind('click', onSave);
        $('#btn-delete').bind('click', onDelete);
        $('#btn-append').bind('click', onAppend);
    };


    // RETURN PUBLIC METHODS
    //
    return {
        configModule: configModule,
        initModule: initModule
    };
    //------------------- END PUBLIC METHODS ---------------------
}());