/*
    Copyright (C) 2022 Tenable, Inc.

	Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package vulnerability

import (
	"encoding/xml"
	"strings"

	"github.com/google/go-containerregistry/pkg/name"
	"github.com/tenable/terrascan/pkg/iac-providers/output"
	"github.com/tenable/terrascan/pkg/results"
	"go.uber.org/zap"
)

const (
	colon           = ":"
	slash           = "/"
	defaultTagValue = "latest"
	atTheRate       = "@"
	sha256          = "sha256"
)

// VulEngine Implements the vulnerability engine interface
type VulEngine struct {
	results EngineOutput
}

// EngineInput holds input for vulnerability engine
type EngineInput struct {
	InputData *output.AllResourceConfigs
}

// EngineOutput Contains data output from the engine
type EngineOutput struct {
	XMLName                 xml.Name `json:"-" yaml:"-" xml:"results"`
	*results.ViolationStore `json:"results" yaml:"results" xml:"results"`
}

// ImageDetails will hold details about the image being scanned for vulnerabilities.
type ImageDetails struct {
	Tag        string `json:"tag"`
	Digest     string `json:"digest"`
	Name       string `json:"name"`
	Repository string `json:"repository"`
	Registry   string `json:"registry"`
}

// GetImageDetails finds image component from image name
func GetImageDetails(image string, imageDetails ImageDetails) ImageDetails {
	base := image
	imageSha256SplitToken := atTheRate + sha256 + colon
	if strings.Contains(image, imageSha256SplitToken) {
		parts := strings.Split(image, imageSha256SplitToken)
		if len(parts) >= 2 {
			base = strings.Join(parts[:len(parts)-1], "")
			imageDetails.Digest = sha256 + colon + parts[len(parts)-1]
		}
		return GetImageDetails(base, imageDetails)
	}
	parts := strings.Split(image, colon)
	if len(parts) > 1 && !strings.Contains(parts[len(parts)-1], slash) {
		base = strings.Join(parts[:len(parts)-1], colon)
		imageDetails.Tag = parts[len(parts)-1]
	}

	imageDetails.Repository = GetRepository(base)
	imageDetails.Registry = strings.Split(image, slash+imageDetails.Repository)[0]
	return imageDetails
}

// GetRepository finds repository from image name
func GetRepository(image string) (repository string) {
	parts := strings.SplitN(image, slash, 2)
	if len(parts) == 2 && (strings.ContainsRune(parts[0], '.') || strings.ContainsRune(parts[0], ':')) {
		repository = parts[1]
	}
	return
}

// GetDomain get image domain from image name
func GetDomain(image string) string {
	var nameOpts []name.Option
	ref, err := name.ParseReference(image, nameOpts...)
	if err != nil {
		zap.S().Error(invalidImageReferenceMsg, image)
		return ""
	}
	domain := ref.Context().RegistryStr()
	return domain
}
