/*
 * This file is part of the Meeds project (https://meeds.io/).
 * 
 * Copyright (C) 2020 - 2022 Meeds Association contact@meeds.io
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package io.meeds.tenant.provisioning.web.rest;

import static io.meeds.tenant.provisioning.web.rest.utils.EntityMapper.mergeObjects;
import static io.meeds.tenant.provisioning.web.rest.utils.EntityMapper.toMap;
import static io.meeds.tenant.provisioning.web.rest.utils.EntityMapper.toObject;

import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.server.ResponseStatusException;

import io.meeds.deeds.constant.ObjectNotFoundException;
import io.meeds.tenant.provisioning.service.TenantProvisioningService;
import io.meeds.tenant.provisioning.service.TenantProvisioningSettingsService;
import io.meeds.tenant.provisioning.web.model.DeedTenantProvisioningSettings;

@RestController
@RequestMapping("/api/provisioning/settings")
public class TenantProvisioningSettingsController {

  private static final Logger               LOG = LoggerFactory.getLogger(TenantProvisioningSettingsController.class);

  @Autowired
  private TenantProvisioningService         tenantProvisioningService;

  @Autowired
  private TenantProvisioningSettingsService tenantProvisioningSettingsService;

  @GetMapping
  public ResponseEntity<DeedTenantProvisioningSettings> getSettings(Principal principal) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    Map<String, Object> settingsMap = tenantProvisioningSettingsService.getSettings();
    DeedTenantProvisioningSettings settings = toObject(settingsMap, DeedTenantProvisioningSettings.class);
    return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(settings);
  }

  @PatchMapping
  public ResponseEntity<DeedTenantProvisioningSettings> saveSettings(Principal principal,
                                                                     @RequestParam
                                                                     Map<Object, Object> fields) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    if (fields == null) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Empty Settings");
    }
    DeedTenantProvisioningSettings settings = mergeSettings(fields);
    Map<String, Object> settingsMap = toMap(settings);
    try {
      tenantProvisioningSettingsService.saveSettings(settingsMap, principal.getName());
    } catch (ObjectNotFoundException e) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Can't upload logo");
    }
    return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(settings);
  }

  @GetMapping("/logo")
  public void getEmailLogo(Principal principal, HttpServletResponse response) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    InputStream emailLogoInputstream = tenantProvisioningSettingsService.getEmailLogo();
    response.setContentType(MediaType.IMAGE_PNG_VALUE);
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    try {
      IOUtils.copy(emailLogoInputstream, response.getOutputStream());
    } catch (IOException e) {
      throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
      try {
        emailLogoInputstream.close();
      } catch (IOException e) {
        LOG.warn("Error while closing input stream of logo file", e);
      }
    }
  }

  private DeedTenantProvisioningSettings mergeSettings(Map<Object, Object> fields) {
    DeedTenantProvisioningSettings newValues = toObject(fields, DeedTenantProvisioningSettings.class);
    Map<String, Object> settingsMap = tenantProvisioningSettingsService.getSettings();
    return mergeObjects(toObject(settingsMap, DeedTenantProvisioningSettings.class), newValues);
  }

}
