function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import React, { useRef, useState } from 'react';
import uuidv1 from 'uuid/v1';
import { Chat } from './Chat';
import { dummyChatList, dummyMessagesText } from './dummyMessages';
export var ChatStory = function ChatStory(_ref) {
  var _ref$initialMessages = _ref.initialMessages,
      initialMessages = _ref$initialMessages === void 0 ? [] : _ref$initialMessages,
      _ref$isMaximizedOnly = _ref.isMaximizedOnly,
      isMaximizedOnly = _ref$isMaximizedOnly === void 0 ? false : _ref$isMaximizedOnly,
      error = _ref.error,
      _ref$isBlocked = _ref.isBlocked,
      isBlocked = _ref$isBlocked === void 0 ? false : _ref$isBlocked,
      _ref$blockedMessage = _ref.blockedMessage,
      blockedMessage = _ref$blockedMessage === void 0 ? undefined : _ref$blockedMessage,
      _ref$initialChatList = _ref.initialChatList,
      initialChatList = _ref$initialChatList === void 0 ? [] : _ref$initialChatList,
      warningMessage = _ref.warningMessage;

  var _useState = useState(initialMessages),
      _useState2 = _slicedToArray(_useState, 2),
      messages = _useState2[0],
      setMessages = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isLoading = _useState4[0],
      setIsLoading = _useState4[1];

  var _useState5 = useState(initialChatList),
      _useState6 = _slicedToArray(_useState5, 2),
      chatList = _useState6[0],
      setChatList = _useState6[1];

  var chatClient = useRef(null);
  var totalUnread = useRef(initialChatList.reduce(function (total, c) {
    return total + c.unread;
  }, 0));
  var isMultipleChat = chatList.length > 0;

  var mockStatusMessage = function mockStatusMessage(id, status) {
    setMessages(function (prevMessages) {
      var copyMessages = _toConsumableArray(prevMessages);

      var message = copyMessages.find(function (m) {
        return m.localId === id;
      });
      message.status = status;
      return copyMessages;
    });
  };

  var sendToBackend = function sendToBackend(text, id) {
    // Mocking change state to delivered
    setTimeout(function () {
      return mockStatusMessage(id, 'delivered');
    }, 1000); // Mocking send to a local echo backend

    setTimeout(function () {
      return echoBackend(text);
    }, 3000);
  };

  var echoBackend = function echoBackend(newMessage) {
    setMessages(function (prevMessage) {
      return [].concat(_toConsumableArray(prevMessage), [{
        at: '02/03/2019 10:12',
        own: false,
        id: Date.now().toString(),
        text: newMessage
      }]);
    });
  };

  var sendAudioToBackend = function sendAudioToBackend(blob, id) {
    // Mocking change state to delivered
    setTimeout(function () {
      return mockStatusMessage(id, 'delivered');
    }, 2000); // Mocking send to a local echo backend

    setTimeout(function () {
      return echoAudioBackend(blob);
    }, 4000);
  };

  var echoAudioBackend = function echoAudioBackend(blob) {
    setMessages(function (prevMessage) {
      return [].concat(_toConsumableArray(prevMessage), [{
        at: '02/03/2019 10:12',
        own: false,
        id: Date.now().toString(),
        medias: [{
          mediaType: 'audio',
          url: blob.blobURL
        }]
      }]);
    });
  };

  var sendMediaToBackend = function sendMediaToBackend(file, title, id, noTitle) {
    // Mocking change state to delivered
    setTimeout(function () {
      return mockStatusMessage(id, 'delivered');
    }, 2000); // Mocking send to a local echo backend

    setTimeout(function () {
      return echoMediaBackend(file, title, noTitle);
    }, 5000);
  };

  var echoMediaBackend = function echoMediaBackend(file, title, noTitle) {
    setMessages(function (prevMessage) {
      return [].concat(_toConsumableArray(prevMessage), [{
        at: '02/03/2019 10:12',
        own: false,
        id: Date.now().toString(),
        medias: [{
          mediaType: file.mediaType,
          url: file.data,
          name: file.name // size: file.size, emulate scenario without size from backend

        }],
        title: noTitle ? undefined : title
      }]);
    });
  };

  var onMessageSend = function onMessageSend(text) {
    var localId = uuidv1();
    setMessages(function (prevMessages) {
      var copyPrevMessages = _toConsumableArray(prevMessages);

      copyPrevMessages.push({
        at: '02/03/2019 10:12',
        own: true,
        id: Date.now().toString(),
        authorName: 'Você',
        status: 'sending',
        text: text,
        localId: localId
      });
      return copyPrevMessages;
    });

    if (!error) {
      sendToBackend(text, localId);
    }
  };

  var onAudioSend = function onAudioSend(blob) {
    if (blob !== null) {
      var localId = uuidv1();
      setMessages(function (prevMessages) {
        var copyPrevMessages = _toConsumableArray(prevMessages);

        copyPrevMessages.push({
          at: '02/03/2019 10:12',
          own: true,
          id: Date.now().toString(),
          authorName: 'Você',
          status: 'sending',
          localId: localId,
          medias: [{
            mediaType: 'audio',
            url: blob.blobURL
          }]
        });
        return copyPrevMessages;
      });

      if (!error) {
        sendAudioToBackend(blob, localId);
      }
    }
  };

  var onMediaSend = function onMediaSend(title, files) {
    if (files !== null) {
      var titleAsMessage = Object.keys(files).length > 1 || files[Object.keys(files)[0]] !== undefined && files[Object.keys(files)[0]].mediaType.startsWith('application');
      Object.keys(files).forEach(function (uid, i) {
        var localId = uuidv1();
        setMessages(function (prevMessages) {
          var copyPrevMessages = _toConsumableArray(prevMessages);

          copyPrevMessages.push({
            at: '02/03/2019 10:12',
            own: true,
            id: Date.now().toString(),
            authorName: 'Você',
            status: 'sending',
            localId: localId,
            medias: [{
              mediaType: files[uid].mediaType,
              url: files[uid].data,
              name: files[uid].name,
              size: files[uid].size
            }],
            title: titleAsMessage ? undefined : title
          });
          return copyPrevMessages;
        });

        if (!error) {
          sendMediaToBackend(files[uid], title, localId, titleAsMessage);
        }
      });

      if (titleAsMessage) {
        onMessageSend(title);
      }
    }
  };

  var onMessageResend = function onMessageResend(id) {
    // mock sending to backend
    mockStatusMessage(id, 'sending'); // mock error again sending the message

    setTimeout(function () {
      return mockStatusMessage(id, 'error');
    }, 1000);
  };

  var onBackToChatList = function onBackToChatList() {
    // States to unset client
    chatClient.current = null;
    setMessages([]); // Dummy fetch chat list

    setIsLoading(true);
    setTimeout(function () {
      // Count total unread
      totalUnread.current = dummyChatList.reduce(function (total, c) {
        return total + c.unread;
      }, 0); // Set the array

      setChatList(_toConsumableArray(dummyChatList));
      setIsLoading(false);
    }, 2000);
  };

  var onSelectedChat = function onSelectedChat(chatClintClicked) {
    chatClient.current = chatClintClicked; // Dummy fetch chat messages of chatClintClicked.chatId

    setIsLoading(true);
    setTimeout(function () {
      setMessages(_toConsumableArray(dummyMessagesText));
      setIsLoading(false);
    }, 3000);
  };

  var getSubtitle = function getSubtitle(defaultSub) {
    if (chatClient.current !== null) {
      return "".concat(chatClient.current.name, " - ").concat(chatClient.current.phone);
    }

    return defaultSub;
  }; // Defined according how is using the chat: with contact list or simple


  var defaultSub = isMultipleChat > 0 ? "".concat(totalUnread.current, " mensagens n\xE3o lidas") : 'Última mensagem 10/10/2019 10:10';
  return React.createElement("div", {
    style: {
      width: '400px',
      height: '550px',
      position: 'fixed',
      right: '1em',
      bottom: '-50px'
    }
  }, React.createElement(Chat, {
    error: error,
    isMaximizedOnly: isMaximizedOnly,
    isBlocked: isBlocked,
    blockedMessage: blockedMessage,
    messages: messages,
    title: isMultipleChat ? 'Transportadora Gomes' : 'Felipe Rodrigues',
    subtitle: getSubtitle(defaultSub),
    onMessageSend: onMessageSend,
    onAudio: onAudioSend,
    onMediaSend: onMediaSend,
    onMessageResend: onMessageResend,
    isLoading: isLoading,
    chatList: isMultipleChat > 0 ? chatList : undefined,
    notificationNumber: totalUnread.current,
    onBackToChatList: onBackToChatList,
    onSelectedChat: onSelectedChat,
    warningMessage: warningMessage,
    customHeader: {
      headerBackground: '#f7f7f7',
      headerText: '#000'
    }
  }));
};