import jwtDecode from 'jwt-decode';
import { API_SIGN_IN, CODE_OK, CODE_NONCE_MISMATCH, CODE_TOKEN_INVALID } from '../../common';
import { WS_API, createFailureFromAction } from '../../store/wsAPI';

export const generateNonce = (len = 20) => {
  const arr = new Uint8Array(len / 2);
  window.crypto.getRandomValues(arr);
  return Array.from(arr, val => val.toString(16)).join('');
};

const decodeToken = token => jwtDecode(token);

const checkResponse = ({ request, response }) => {
  let decodedToken;
  try {
    decodedToken = decodeToken(response.response.token);
  } catch (error) {
    return {
      code: CODE_TOKEN_INVALID,
      status: 'Špatný přihlašovací token. Zkus se přihlásit znovu.',
      token: response.response.token
    };
  }

  if (decodedToken.nonce === request.nonce) {
    return { code: CODE_OK, decodedToken };
  }

  return {
    code: CODE_NONCE_MISMATCH,
    status:
      'Jednorázový přihlašovací kód vygenerovaný prohlížečem nesouhlasí s kódem, který poslal server.',
    client: request.nonce,
    server: decodedToken.nonce
  };
};

const normalize = ({
  request,
  response: {
    check: { client, code, decodedToken, server, status } = {},
    response: { token, username }
  }
}) => ({ request, response: { client, code, decodedToken, server, status, token, username } });

export const SIGN_IN = 'SIGN_IN';
export const signIn = ({ username, password }) => ({
  [WS_API]: {
    type: SIGN_IN,
    checkResponse,
    dontUseToken: true,
    endpoint: API_SIGN_IN,
    normalize,
    request: () => ({ username, password, nonce: generateNonce() }),
    title: 'přihlašování'
  }
});

// :TODO: used only by legacy code. Remove when not needed.
export const authTokenExpired = ({ response, ...rest }) =>
  createFailureFromAction({
    ...rest,
    action: signIn({}),
    response: {
      ...response,
      status: `Platnost ověřovacího tokenu pravděpodobně vypršela. ${response.status}`
    }
  });

@@ -142,33 +142,8 @@
 _API
-, createFailureFromAction
  %7D f
@@ -1598,323 +1598,4 @@
 %7D);%0A
-%0A// :TODO: used only by legacy code. Remove when not needed.%0Aexport const authTokenExpired = (%7B response, ...rest %7D) =%3E%0A  createFailureFromAction(%7B%0A    ...rest,%0A    action: signIn(%7B%7D),%0A    response: %7B%0A      ...response,%0A      status: %60Platnost ov%C4%9B%C5%99ovac%C3%ADho tokenu pravd%C4%9Bpodobn%C4%9B vypr%C5%A1ela. $%7Bresponse.status%7D%60%0A    %7D%0A  %7D);%0A

Remove cruft.