Completed
Branch master (ebb499)
by Alexey
04:15
created

inji.Chats.get   C

Complexity

Conditions 10
Paths 12

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 12
nop 0
dl 0
loc 24
rs 5.2164
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like inji.Chats.get often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
inji.Chats = {};
2
inji.Chats.chats = [];
3
inji.Chats.get = function (id, params) {
4
  var chatElement = $('#' + id);
5
  var chat;
0 ignored issues
show
Unused Code introduced by
The variable chat seems to be never used. Consider removing it.
Loading history...
6
  if (chatElement.data('chats-index') === undefined) {
7
    inji.Chats.chats.push({
8
      element: chatElement,
9
      timer: null,
10
      chatId: chatElement.data('chat-id'),
11
      msgCount: chatElement.data('msg-count'),
12
      perPage: 20,
13
      lastEventDate: chatElement.data('last-event-date'),
14
      reverse: params.reverse ? true : false,
15
      scrollable: true,
16
      members: {},
17
      checkoutMembers: function () {
18
        var members = this.members;
19
        $.each($('[data-chat_member_status'), function () {
20
          var el = $(this);
21
          if (members[el.data('chat_member_status')]) {
22
            if (el.data('ontext')) {
23
              el.html(el.data('ontext'));
24
            }
25
            if (el.data('onclass')) {
26
              if (el.data('offclass') && el.hasClass(el.data('offclass'))) {
27
                el.removeClass(el.data('offclass'));
28
              }
29
              el.addClass(el.data('onclass'));
30
            }
31
          } else {
32
            if (el.data('offtext')) {
33
              el.html(el.data('offtext'));
34
            }
35
            if (el.data('offclass')) {
36
              if (el.data('onclass') && el.hasClass(el.data('onclass'))) {
37
                el.removeClass(el.data('onclass'));
38
              }
39
              el.addClass(el.data('offclass'));
40
            }
41
          }
42
        })
43
      },
44
      deleteMsg: function (id, chatId) {
45
        inji.Server.request({
46
          url: 'chats/deleteMsg/' + id,
47
          success: function () {
48
            $('#chat' + chatId + 'msg' + id).remove();
49
          }
50
        });
51
      },
52
      banUser: function (msgId, chatId) {
53
        inji.Server.request({
54
          url: 'chats/banUser/' + msgId,
55
          success: function (msgIds) {
56
            for (var key in msgIds) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
57
              $('#chat' + chatId + 'msg' + key).remove();
58
            }
59
          }
60
        });
61
      },
62
    });
63
    var index = inji.Chats.chats.length - 1
64
    chatElement.data('chats-index', index);
65
    inji.Chats.init(index);
66
    return inji.Chats.chats[index];
67
  }
68
  return inji.Chats.chats[chatElement.data('chats-index')];
69
}
70
inji.Chats.init = function (chatIndex) {
71
  var updater = function () {
72
    inji.Server.request({
73
      url: 'chats/events/' + inji.Chats.chats[chatIndex].chatId,
74
      data: {
75
        lastEventDate: inji.Chats.chats[chatIndex].lastEventDate
76
      },
77
      success: function (data) {
78
        inji.Chats.chats[chatIndex].members = data.members;
79
        inji.Chats.chats[chatIndex].checkoutMembers();
80
        for (key in data.messages) {
0 ignored issues
show
Bug introduced by
The variable key seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.key.
Loading history...
81
          var msg = data.messages[key];
82
          inji.Chats.chats[chatIndex].lastEventDate = msg.message.chat_message_date_create;
83
          var template = inji.Chats.chats[chatIndex].element.find('.chats-chat-message-template').html();
84
          template = template.replace(/message-id/g, msg.message.chat_message_id);
85
          template = template.replace(/message-userId/g, msg.message.chat_message_user_id);
86
          template = template.replace(/message-date_create/g, msg.message.chat_message_date_create);
87
          template = template.replace(/user-firstName/g, msg.userFirstName);
88
          template = template.replace(/user-fullName/g, msg.fullUserName);
89
          template = template.replace(/user-photo/g, msg.userPhoto);
90
          template = template.replace(/message-text/g, msg.message.chat_message_text);
91
          var messageList = inji.Chats.chats[chatIndex].element.find('.chats-chat-messageList');
92
          if (inji.Chats.chats[chatIndex].reverse) {
93
            messageList.append(template);
94
            if (inji.Chats.chats[chatIndex].scrollable) {
95
              var height = messageList.height() + messageList.scrollTop() + parseInt(messageList.css('paddingTop')) + parseInt(messageList.css('paddingBottom'));
96
              messageList.scrollTop(messageList[0].scrollHeight);
97
            }
98
          } else {
99
            messageList.prepend(template);
100
          }
101
        }
102
103
        var allMsgs = inji.Chats.chats[chatIndex].element.find('.chats-chat-messageList>*');
104
        if (allMsgs.length > 20) {
105
          var i = 0;
106
          if (inji.Chats.chats[chatIndex].reverse) {
107
            var diff = allMsgs.length - 20;
108
            while (i <= diff && i >= 0) {
109
              $(allMsgs[i]).remove();
110
              i--;
111
            }
112
          } else {
113
            i = allMsgs.length + 1;
114
            while (i > 20 && allMsgs[i]) {
115
              $(allMsgs[i]).remove();
116
              i++;
117
            }
118
          }
119
        }
120
      }
121
    });
122
  };
123
  updater();
124
  inji.Chats.chats[chatIndex].timer = setInterval(updater, 5000);
125
}
126
inji.Chats.sendForm = function (form, id) {
127
  var chat = inji.Chats.get(id);
128
  var formData = new FormData(form);
129
  inji.Server.request({
130
    url: '/chats/sendForm/' + chat.element.data('chat-id'),
131
    type: 'POST',
132
    data: formData,
133
    processData: false,
134
  });
135
}