package com.iqser.red.service.persistence.management.v1.processor.service;

import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.service.v1.api.shared.model.license.Feature;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.FeatureType;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.License;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.RedactionLicenseModel;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class LicenseUtilityService {

    public static final String LICENSE_OBJECT_ID = "license/redact-manager-license.json";
    public static final String DEMO_PDFTRON_LICENSE = "demo:1650351709282:7bd235e003000000004ec28a6743e1163a085e2115de2536ab6e2cfe5a";
    public static final String LICENSE_CUSTOMER = "LICENSE_CUSTOMER";
    public static final String LICENSE_START = "LICENSE_START";
    public static final String LICENSE_END = "LICENSE_END";
    public static final String LICENSE_PAGE_COUNT = "LICENSE_PAGE_COUNT";
    public static final String LICENSE_MS_OFFICE_FORMATS = "LICENSE_SUPPORT_MS_OFFICE_FORMATS";
    public static final String PDFTRON_FRONTEND_LICENSE = "PDFTRON_FRONTEND_LICENSE";
    public static final String CONFIGURABLE_SMTP_SERVER = "CONFIGURABLE_SMTP_SERVER";
    public static final String PDFTRON_FEATURE = "pdftron";
    public static final String PROCESSING_PAGES_FEATURE = "processingPages";
    public static final String DEFAULT_PROCESSING_PAGES = "200000";
    public static final String SUPPORT_MS_OFFICE_FORMATS_FEATURE = "supportMSOfficeFormats";
    public static final String DEFAULT_SUPPORT_MS_OFFICE_FORMATS = "false";
    public static final String CONFIGURABLE_SMTP_SERVER_FEATURE = "configurableSMTPServer";
    public static final String DEFAULT_CONFIGURABLE_SMTP_SERVER = "false";

    public static final List<String> ALL_FILE_FORMATS = List.of("pdf", "docx", "doc", "xls", "xlsx", "ppt", "pptx");
    public static final List<String> FILE_FORMATS_EXCLUDING_MS_OFFICE = List.of("pdf");

    private final Environment environment;


    public RedactionLicenseModel generateDemoLicense() {

        License demo = new License();
        demo.setId("RedactManager");
        demo.setName("RedactManager License");
        demo.setProduct("RedactManager");

        var licensedTo = environment.getProperty(LICENSE_CUSTOMER, "RedactManager Demo License");
        demo.setLicensedTo(licensedTo);

        var licenseStartDate = parseDate(environment.getProperty(LICENSE_START));
        var start = licenseStartDate != null ? licenseStartDate : OffsetDateTime.now().withDayOfYear(1).withHour(0).withMinute(0).withSecond(0).truncatedTo(ChronoUnit.SECONDS);
        demo.setValidFrom(start);

        var licenseEndDate = parseDate(environment.getProperty(LICENSE_END));
        var end = licenseEndDate != null ? licenseEndDate : OffsetDateTime.now()
                .withMonth(12)
                .withDayOfMonth(31)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .truncatedTo(ChronoUnit.SECONDS);
        demo.setValidUntil(end);

        var pdftronLicense = environment.getProperty(PDFTRON_FRONTEND_LICENSE, DEMO_PDFTRON_LICENSE);
        demo.getFeatures().add(Feature.builder().name(PDFTRON_FEATURE).type(FeatureType.STRING).value(pdftronLicense).build());

        var pageCount = Long.parseLong(environment.getProperty(LICENSE_PAGE_COUNT, DEFAULT_PROCESSING_PAGES));
        demo.getFeatures().add(Feature.builder().name(PROCESSING_PAGES_FEATURE).type(FeatureType.NUMBER).value(pageCount).build());

        boolean supportMSOfficeFormats = Boolean.parseBoolean(environment.getProperty(LICENSE_MS_OFFICE_FORMATS, DEFAULT_SUPPORT_MS_OFFICE_FORMATS));
        demo.getFeatures().add(Feature.builder().name(SUPPORT_MS_OFFICE_FORMATS_FEATURE).type(FeatureType.BOOLEAN).value(supportMSOfficeFormats).build());

        boolean configurableSMTPServer = Boolean.parseBoolean(environment.getProperty(CONFIGURABLE_SMTP_SERVER, DEFAULT_CONFIGURABLE_SMTP_SERVER));
        demo.getFeatures().add(Feature.builder().name(CONFIGURABLE_SMTP_SERVER_FEATURE).type(FeatureType.BOOLEAN).value(configurableSMTPServer).build());

        var demoLicense = new RedactionLicenseModel();
        demoLicense.setActiveLicense("RedactManager");
        demoLicense.getLicenses().add(demo);

        return demoLicense;
    }


    private OffsetDateTime parseDate(String date) {

        if (StringUtils.isEmpty(date)) {
            return null;
        }
        var parts = date.split("-");
        if (parts.length != 3) {
            return null;
        }

        try {
            return OffsetDateTime.now()
                    .withYear(Integer.parseInt(parts[2]))
                    .withMonth(Integer.parseInt(parts[1]))
                    .withDayOfMonth(Integer.parseInt(parts[0]))
                    .withHour(0)
                    .withMinute(0)
                    .withSecond(0)
                    .truncatedTo(ChronoUnit.SECONDS);
        } catch (Exception e) {
            log.debug("Failed to parse date: {}", date);
            return null;
        }

    }

}
