/*
 * 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.fromDTO;
import static io.meeds.tenant.provisioning.web.rest.utils.EntityMapper.toDTO;

import java.security.Principal;
import java.util.List;

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.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
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 org.exoplatform.commons.ObjectAlreadyExistsException;

import io.meeds.deeds.constant.ObjectNotFoundException;
import io.meeds.tenant.provisioning.model.EmailTemplate;
import io.meeds.tenant.provisioning.model.EmailTemplateDTO;
import io.meeds.tenant.provisioning.service.DeedEmailService;
import io.meeds.tenant.provisioning.service.TenantProvisioningService;

@RestController
@RequestMapping("/api/provisioning/email")
public class DeedEmailController {

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

  @Autowired
  private TenantProvisioningService      tenantProvisioningService;

  @Autowired
  private DeedEmailService deedEmailService;

  @PostMapping
  public void sendEmail(Principal principal,
                        @RequestParam("nftId")
                        long nftId,
                        @RequestParam("subject")
                        String subject,
                        @RequestParam("content")
                        String content) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    try {
      deedEmailService.sendEmail(nftId, subject, content, false);
    } catch (ObjectNotFoundException e) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    } catch (Exception e) {
      LOG.warn("Error sending email to tenant manager", e);
      throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @GetMapping("templates")
  public ResponseEntity<List<EmailTemplateDTO>> getEmailTemplates(Principal principal) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    List<EmailTemplate> emailTemplates = deedEmailService.getEmailTemplates();
    return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(toDTO(emailTemplates));
  }

  @PostMapping("templates")
  public ResponseEntity<EmailTemplateDTO> createTemplate(Principal principal,
                                                         @RequestBody
                                                         EmailTemplateDTO emailTemplate) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    if (emailTemplate == null) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "emailTemplate object is mandatory");
    }
    if (StringUtils.isNotBlank(emailTemplate.getId())) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "emailTemplate.id has to be empty");
    }
    try {
      EmailTemplate createdEmailTemplate = deedEmailService.createTemplate(fromDTO(emailTemplate));
      return ResponseEntity.ok().body(toDTO(createdEmailTemplate));
    } catch (ObjectAlreadyExistsException e) {
      throw new ResponseStatusException(HttpStatus.CONFLICT, "Id already exists");
    }
  }

  @PutMapping("templates/{id}")
  public ResponseEntity<EmailTemplateDTO> updateTemplate(Principal principal,
                                                         @PathVariable("id")
                                                         String id,
                                                         @RequestBody
                                                         EmailTemplateDTO emailTemplate) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    if (StringUtils.isBlank(id)) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id is mandatory");
    }
    if (emailTemplate == null) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "emailTemplate object is mandatory");
    }
    emailTemplate.setId(id);
    try {
      EmailTemplate createdEmailTemplate = deedEmailService.updateTemplate(fromDTO(emailTemplate));
      return ResponseEntity.ok().body(toDTO(createdEmailTemplate));
    } catch (ObjectNotFoundException e) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
  }

  @DeleteMapping("templates/{id}")
  public void deleteTemplate(Principal principal,
                             @PathVariable("id")
                             String id) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    if (StringUtils.isBlank(id)) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id is mandatory");
    }
    try {
      deedEmailService.deleteTemplate(id);
    } catch (ObjectNotFoundException e) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
  }

}
