package kz.uco.callcenter.web.controllers;

import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.core.sys.SecurityContext;
import com.haulmont.cuba.security.app.TrustedClientService;
import com.haulmont.cuba.security.global.LoginException;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.auth.WebAuthConfig;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import kz.uco.callcenter.service.AtsManagerService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import static kz.uco.base.common.Null.isEmpty;
import static kz.uco.base.entity.callcenter.Call.NO_AUDIO_RECORD;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;

/**
 * Сервис для загрузки аудиозвонка с удалённой БД и передачи его UI компоненту потоком
 * (рестом потому что UI компонент плеер вызывает http запрос)
 */
@RestController
@RequestMapping("/audio/v1")
public class TalkRecordProvideRestController {

    protected final Logger log = LoggerFactory.getLogger(TalkRecordProvideRestController.class);

    @Inject
    protected AtsManagerService atsManagerService;
    @Inject
    protected TrustedClientService trustedClientService;
    @Inject
    protected WebAuthConfig webAuthConfig;


    @GetMapping("/audio")
    @Async
    public ResponseEntity<StreamingResponseBody> downloadAudio(
            @RequestParam("uniqueId") String uniqueId,
            @RequestParam("atsCode") String atsCode
    ) {
        initSecurityContext();

        String audioRecordFilePath = atsManagerService.getAudioRecordFilePath(uniqueId, atsCode);
        if (NO_AUDIO_RECORD.equals(audioRecordFilePath)) return null;
        audioRecordFilePath = getAccessibleFilePath(atsCode, audioRecordFilePath);

        InputStream fileInputStream = null;
        long fileSize = 0;
        String fileName = null;

        if (atsManagerService.isSambaAccessUsed(atsCode)) {
            try {
            System.setProperty("jcifs.smb.lmCompatibility", "1");

            String sambaUser = atsManagerService.getSambaUser(atsCode);
            String sambaPassword = atsManagerService.getSambaPassword(atsCode);

            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", sambaUser, sambaPassword);
                SmbFile sambaFile = new SmbFile(audioRecordFilePath, auth);
                fileSize = sambaFile.length();
                fileName = sambaFile.getName();
                fileInputStream = new SmbFileInputStream(sambaFile);
            } catch (Exception e) {
                log.info("Error accessing samba file: " + ExceptionUtils.getMessage(e));
            }
        } else {
            try {
                File localFile = new File(audioRecordFilePath);
                fileSize = localFile.length();
                fileName = localFile.getName();
                fileInputStream = new FileInputStream(localFile);
            } catch (FileNotFoundException e) {
                log.info("Error accessing local file: " + ExceptionUtils.getMessage(e));
            }
        }

        if (fileInputStream != null) {
            InputStream inputStream = fileInputStream;
            StreamingResponseBody responseBody = outputStream -> FileCopyUtils.copy(inputStream, outputStream);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
//                    .header("Content-Type", "audio/wav")
                    .contentLength(fileSize)
                    .header("accept-ranges", "bytes")
                    .body(responseBody);
        }
        return null;
    }

    /**
     * Возвращает путь к файлу в расшаренной папке по исходному пути указанному в БД
     */
    protected String getAccessibleFilePath(@Nonnull String atsCode, @Nonnull String audioRecordFilePath) {
        String pathFromReplace = atsManagerService.getPathFromReplace(atsCode);
        String pathToReplace = atsManagerService.getPathToReplace(atsCode);

        if (isEmpty(pathFromReplace) && isEmpty(pathToReplace)) {
            return audioRecordFilePath;

        } else if (isEmpty(pathFromReplace) && isNotEmpty(pathToReplace)) {
            return pathToReplace + audioRecordFilePath;

        } else if (isNotEmpty(pathFromReplace) && isNotEmpty(pathToReplace)) {
            return audioRecordFilePath.replace(pathFromReplace, "");

        } else {
            return audioRecordFilePath.replace(pathFromReplace, pathToReplace);
        }
    }

    protected void initSecurityContext() {
        // Авторизация в cuba
        if (AppContext.getSecurityContext() == null) {
            UserSession systemSession = null;
            try {
                systemSession = trustedClientService.getSystemSession(webAuthConfig.getTrustedClientPassword());
            } catch (LoginException e) {
                e.printStackTrace();
            }
            AppContext.setSecurityContext(new SecurityContext(systemSession));
        }
    }

}
