/*
 * 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.toRestDTOs;

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

import org.apache.commons.lang3.StringUtils;
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.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.blockchain.BlockchainConfigurationProperties;
import io.meeds.deeds.constant.ObjectNotFoundException;
import io.meeds.deeds.constant.TenantProvisioningStatus;
import io.meeds.deeds.constant.TenantStatus;
import io.meeds.deeds.elasticsearch.model.DeedTenant;
import io.meeds.tenant.provisioning.TenantProvisioningConfiguration;
import io.meeds.tenant.provisioning.service.TenantProvisioningService;
import io.meeds.tenant.provisioning.web.model.DeedTenantProvisioningList;

@RestController
@RequestMapping("/api/provisioning/tenants")
public class TenantProvisioningController {

  @Autowired
  private TenantProvisioningConfiguration   provisioningConfiguration;

  @Autowired
  private BlockchainConfigurationProperties blockchainProperties;

  @Autowired
  private TenantProvisioningService         tenantProvisioningService;

  @GetMapping
  public ResponseEntity<DeedTenantProvisioningList> getTenants(Principal principal, @RequestParam(name = "tenantProvisioningStatus", required = false)
  TenantProvisioningStatus provisioningStatus, @RequestParam(name = "includeCompleted", required = false)
  boolean includeCompleted, @RequestParam(name = "limit", required = false)
  int limit) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    if (limit <= 0) {
      limit = 10;
    }
    DeedTenantProvisioningList tenantProvisioningList =
                                                      getDeedTenantProvisioningList(provisioningStatus, includeCompleted, limit);
    return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(tenantProvisioningList);
  }

  @PatchMapping("/{nftId}")
  public void saveTenantStatus(Principal principal,
                               @PathVariable("nftId")
                               long nftId,
                               @RequestParam("tenantStatus")
                               TenantStatus tenantStatus) {
    if (principal == null || StringUtils.isBlank(principal.getName())
        || !tenantProvisioningService.isManager(principal.getName())) {
      throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    if (tenantStatus == null) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Empty Tenant Status field");
    }
    try {
      tenantProvisioningService.saveDeedTenantStatus(nftId, tenantStatus);
    } catch (ObjectNotFoundException e) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Can't find NFT with id " + nftId);
    }
  }

  private DeedTenantProvisioningList getDeedTenantProvisioningList(TenantProvisioningStatus provisioningStatus, boolean includeCompleted, int limit) {
    DeedTenantProvisioningList tenantProvisioningList = new DeedTenantProvisioningList(limit);
    if (provisioningStatus == null) {
      addAllDeedTenants(tenantProvisioningList, includeCompleted, limit);
    } else {
      addDeedTenantsByProvisioningStatus(tenantProvisioningList, provisioningStatus, includeCompleted, limit);
    }
    return tenantProvisioningList;
  }

  private void addAllDeedTenants(DeedTenantProvisioningList tenantProvisioningList, boolean includeCompleted, int limit) {
    Arrays.stream(TenantProvisioningStatus.values())
          .forEach(tenantProvisioningStatus -> addDeedTenantsByProvisioningStatus(tenantProvisioningList,
                                                                                  tenantProvisioningStatus,
                                                                                  includeCompleted,
                                                                                  limit));
  }

  private void addDeedTenantsByProvisioningStatus(DeedTenantProvisioningList tenantProvisioningList, TenantProvisioningStatus tenantProvisioningStatus, boolean includeCompleted, int limit) {
    List<DeedTenant> deedTenants = tenantProvisioningService.getTenants(tenantProvisioningStatus, includeCompleted, limit);
    long count = tenantProvisioningService.getTenantsCount(tenantProvisioningStatus, includeCompleted);
    tenantProvisioningList.addTenantProvisioningStatus(tenantProvisioningStatus,
                                                       toRestDTOs(deedTenants,
                                                                  provisioningConfiguration.getEtherscanPrefix(),
                                                                  blockchainProperties.getDeedAddress()),
                                                       count);
  }

}
