import { ofType } from 'redux-observable';
import { concat, merge, of, Subject } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { catchError, concatMap, map, switchMap } from 'rxjs/operators';

import { TYPE_ERROR, TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { dictionaryBlockInfoComputedSelector } from '../selectors';
import {
  saveConfigurationDataOnServerAction,
  updateConfigurationByPropAction,
  uploadConfigFileAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  query s3ConfigurationFileUploadLink($filename: String!, $bucket: String!, $key: String!) {
    s3ConfigurationFileUploadLink(filename: $filename, bucket: $bucket, key: $key) {
      uploadUrl
      downloadUrl
      filename
      bucket
      key
    }
  }
`;

const replaceFileName = (string, filename) => {
  const keySplit = string.split('/');
  const key = keySplit.slice(0, keySplit.length - 1);
  key.push(filename);

  return key.join('/');
};

export default (action$, state$) =>
  action$.pipe(
    ofType(uploadConfigFileAction.type),
    switchMap(({ payload }) => {
      const { allowedExtensions, dictionary, dictionaryName, fileInfo, multipleLabel } = payload;

      const filename = fileInfo.name;

      const nameSplit = filename.split('.');

      if (allowedExtensions.indexOf(`.${nameSplit[nameSplit.length - 1]}`) === -1) {
        return of(
          showNotificationAction({
            type: TYPE_ERROR,
            message: `Only ${allowedExtensions.join(', ')} files are supported`,
          }),
        );
      }

      const propBucket = dictionaryBlockInfoComputedSelector(state$.value)[dictionaryName];
      let newBucketInfo = null;

      if (multipleLabel) {
        newBucketInfo = propBucket.map((item) => {
          if (item.label === multipleLabel) {
            return {
              label: item.label,
              value: {
                bucket: item.value.bucket,
                key: replaceFileName(item.value.key, filename),
                url: replaceFileName(item.value.url, filename),
              },
            };
          }
          return { ...item };
        });
      } else {
        newBucketInfo = {
          bucket: propBucket.bucket,
          key: replaceFileName(propBucket.key, filename),
          url: replaceFileName(propBucket.url, filename),
        };
      }

      const keySplit = dictionary.key.split('/');
      keySplit[keySplit.length - 1] = filename;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          filename,
          bucket: dictionary.bucket,
          key: keySplit.join('/'),
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          if (!errors.length) {
            const { uploadUrl } = data.s3ConfigurationFileUploadLink;

            const progressSubscriber = new Subject();

            const fileUploadRequest = ajax({
              method: 'PUT',
              url: uploadUrl,
              headers: {
                'Content-Type': 'application/octet-stream',
              },
              crossDomain: true,
              withCredentials: true,
              body: fileInfo,
              progressSubscriber,
            });

            const requestObservable = fileUploadRequest.pipe(
              concatMap(({ status }) => {
                if (status === 200) {
                  return concat(
                    of(
                      updateConfigurationByPropAction({
                        [dictionaryName]: newBucketInfo,
                      }),
                    ),
                    of(saveConfigurationDataOnServerAction([dictionaryName])),
                    of(
                      showNotificationAction({
                        type: TYPE_SUCCESS,
                        message: `File ${filename} uploaded`,
                      }),
                    ),
                  );
                }

                return concat(
                  of(
                    showNotificationAction({
                      type: TYPE_ERROR,
                      message: 'Something went wrong',
                    }),
                  ),
                );
              }),
            );

            const fileUploadSteam = merge(
              progressSubscriber.pipe(map((e) => ({ percentage: e.loaded / e.total }))),
              requestObservable,
            ).pipe(
              catchError((error) =>
                concat(
                  of(
                    showNotificationAction({
                      type: TYPE_ERROR,
                      message: error ?? 'Something went wrong',
                    }),
                  ),
                ),
              ),
            );

            return concat(fileUploadSteam);
          }

          return concat(
            of(
              showNotificationAction({
                type: TYPE_ERROR,
                message: errors[0].message ?? 'Something went wrong',
              }),
            ),
          );
        }),
      );

      return concat(stream$);
    }),
  );
